Register Login

typeerror: 'nonetype' object is not iterable

Updated Dec 03, 2019

This type of error occurs when you try to iterate any objects or variable having or assigned “None” value.

For the better understanding kindly see the following example where we have assigned “none” value to a variable and we are trying to print the value of that variable with the help of “for loop”.

Example:

myvar = None

for x in myvar:
     print("Value of myvar: ", x)

Output:

TypeError: 'NoneType' object is not iterable

In the above example as you can see that we have assigned “none” value to a variable “myvar” and then we have printed the value of variable “myvar” using for loop. As you know “NoneType” is not iterable that is why we are getting this type error as output.

Iterate NoneType value returns from function or method

In python we all know that if a function or method does not return any value but returns “NoneType”. So when we use the same “NoneType” value to iterate, it will generate an error as shown as output in the following example.

Example:

def myfunction(a, b):
    sumofvalue = a + b
    print("Sum of a & b: ", sumofvalue)

mysub = myfunction(10, 17)

for a in mysub:
    print("My Value:", a)

Output:

TypeError: 'NoneType' object is not iterable

In the above example, we have created a function where we are printing the sum of two variable but not returning any value as output.

But in the next line we have taken the output of the function in variable “mysub” and then we have tried to print the value using for loop.

As function “myfunction()” does not return any value so it will return “NoneType” and hence generate an error while printing the value using for loop.

Check your iterate variable for NoneType

To avoid such type of error, you need to check the variable for “NoneType “ while using them in loop.

Example:

myvar = None 
print(myvar is None)
print(myvar is not None)
print(myvar == None)
print(myvar != None)

Output:

True
False
True
False

 


×