4

I am writing a program in Python and am trying to extend a list as such:

spectrum_mass[second] = [1.0, 2.0, 3.0]
spectrum_intensity[second] = [4.0, 5.0, 6.0]
spectrum_mass[first] = [1.0, 34.0, 35.0]
spectrum_intensity[second] = [7.0, 8.0, 9.0]

for i in spectrum_mass[second]:
    if i not in spectrum_mass[first]:
        spectrum_intensity[first].extend(spectrum_intensity[second][spectrum_mass[second].index(i)])
        spectrum_mass[first].extend(i)

However when I try doing this I am getting TypeError: 'float' object is not iterable on line 3.

To be clear, spectrum_mass[second] is a list (that is in a dictionary, second and first are the keys), as is spectrum_intensity[first], spectrum_intensity[second] and spectrum_mass[second]. All lists contain floats.

0

1 Answer 1

15

I am guessing the issue is with the line -

spectrum_intensity[first].extend(spectrum_intensity[second][spectrum_mass[second].index(i)])

extend() function expects an iterable , but you are trying to give it a float. Same behavior in a very smaller example -

>>> l = [1,2]
>>> l.extend(1.2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object is not iterable

You want to use .append() instead -

spectrum_intensity[first].append(spectrum_intensity[second][spectrum_mass[second].index(i)]) 

Same issue in the next line as well , use append() instead of extend() for -

spectrum_mass[first].extend(i)
Sign up to request clarification or add additional context in comments.

3 Comments

Good question, good answer, and I was not able to find any immediate duplicates either :). Good job.
This seems like a sensible place to link to this SO question about the difference between append and extend.
I also learned something from this SO discussion on a similar subject.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.