‘float’ object is not iterable – Python Error

Total
0
Shares

Python throws error, ‘float’ object is not iterable, when we try to loop over a float object. Float values are not iterable in nature.

Consider this example –

pi = 22 / 7
for i in pi:
    print(i)

# Error: 'float' object is not iterable

This code will throw the float not iterable error because you cannot loop over float value like pi.

First of all you need to understand the usecase. Why do you need to loop over float? Is it actually a loop over list of float items? Or, you want to print each digit of float value separately?

For all the cases there are solutions but none of them leads to loop over single float value. Suppose you want to loop over list then check this code –

floatList = [1.0, 1.3, 4.2, 5.7, 3.4524]
for i in floatList:
    print(i)

If you want to put each list item in separate list

floatList = [1.0, 1.3, 4.2, 5.7, 3.4524]
newFloatList = []
for i in floatList:
    newFloatList.append([i])

Print each digit of float value separately, you need to cast the value to string first because string is iterable and then convert into characters list using list() function –

pi = 22 / 7
charList = list(str(pi))
for i in charList:
    print(i)

    Tweet this to help others