TypeError: 'float' object is not iterable

Chris Rebert clp2 at rebertia.com
Thu Mar 14 11:50:39 CET 2013


On Thu, Mar 14, 2013 at 3:12 AM, Ana Dionísio <anadionisio257 at gmail.com> wrote:
> Hi!!
>
> I keep having this error and I don't know why: TypeError: 'float' object is not iterable.

In general, in the future, always include the full exception
Traceback, not just the final error message. The extra details this
provides can greatly aid debugging.

> I have this piece of code, that imports to python some data from Excel and saves it in a list:
>
> "
> t_amb = []
>
> for i in range(sh2.nrows):
>     t_amb.append(sh2.cell(i,2).value)

`t_amb` is a list, and you are apparently putting floats (i.e. real
numbers) into it. `t_amb` is a list of floats.
Therefore every item of `t_amb` (i.e. `t_amb[x]`, for any `x` that's
within the bounds of the list's indices) will be a float.
(Also, you may want to rewrite this as a list comprehension;
http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
)

> print t_amb
>
> "
> Here is everything ok.
>
> But then, I need to pass the data again to exel, so I wrote this:
>
> "
> a=8
This duplicate assignment is pointless.

> for b in range (len(t_amb)):
>     a=8
>     for d in t_amb[b]:

Given our earlier conclusion, we likewise know that `t_amb[b]` will be
a float (we merely replaced the arbitrary `x` with `b`). A single
float is a scalar, not a collection, so it's nonsensical to try and
iterate over it like you are in "for d in t_amb[b]:"; a number is not
a list. `t_amb[b]` is a lone number, and numbers contain no
items/elements over which to iterate. Perhaps you want just "d =
t_amb[b]" ? Remember that in a `for` loop, the expression after the
`in` (i.e. `t_amb[b]`) is evaluated only once, at the beginning of the
loop, and not repeatedly. In contrast, assuming this were a valid
`for` loop, `d` would take on different values at each iteration of
the loop.

In any case, it's rarely necessary nowadays to manually iterate over
the range of the length of a list; use `enumerate()` instead;
http://docs.python.org/2/library/functions.html#enumerate

>         a=a+1
>         sheet.write(a,b+1,d)
> "
>
> The error appear in "for d in t_amb[b]:" and I don't understand why. Can you help me?

I hope this explanation has been sufficiently clear. If you haven't
already, you may wish to review the official Python tutorial at
http://docs.python.org/2/tutorial/index.html . You may also find it
helpful to run your program step-by-step in the interactive
interpreter/shell, printing out the values of your variables along the
way so as to understand what your program is doing.

Regards,
Chris


More information about the Python-list mailing list