If you are a python developer, then atleast for once, you would have faced this TypeEerror: ‘NoneType’ object is not iterable, and probably it occurs in iterations like for and while loops.
Explanation of TypeError : ‘NoneType’ object is not iterable
In Python2, ‘NoneType
‘ is the type of None
.
>>> print(type(None)) #Python2
#Output
<type 'NoneType'> #In Python2 the type of None is the 'NoneType' type.
In Python3, ‘NoneType
‘ is the class of None
.
>>> print(type(None)) #Python3
#Output
<class 'NoneType'> #In Python3, the type of None is the 'NoneType' class.
If you run the above code in Python 2 and Python 3, you will find the type of None
is different, as shown in the example.
Iterating over a variable that has value None fails:
If you are iterating a variable of Type ‘None
‘, Python will throw an error ‘NoneType
‘ object is not iterable.
employee=None
for emp in employee:
print("k") #TypeError: 'NoneType' object is not iterable
Python methods return NoneType if they don’t return a value:
One more common occurrence of the ‘NoneType
‘ exception in Python could be if the function does not return anything or when a function returns data of ‘NoneType
.’
def foo():
print("k")
a, b = foo() #TypeError: 'NoneType' object is not iterable
Concatenation of None
and a string:
If you try concatenating two variables, type string
and type None
, then Python will throw a ‘NoneType
‘ error.
bar = "something"
foo = None
print (foo + bar) #TypeError: cannot concatenate 'str' and 'NoneType' objects
How to fix TypeError ‘NoneType’ object is not iterable Python?
Alright, let’s look at the solution for fixing ‘nonetype
‘ errors in Python. If you are doing an iteration with for or while loop, you should check your looping constructs for NoneType
, as shown below.
a = None
print(a is None) #prints True
print(a is not None) #prints False
print(a == None) #prints True
print(a != None) #prints False
print(isinstance(a, object)) #prints True
print(isinstance(a, str)) #prints False
Guido says the only use is to check for ‘None
‘ because it is more robust to identity checking. Don’t use equality operations because those can spit bubble-up implementations of their own. Python’s Coding Style Guidelines – PEP-008
employee=None
if employee is not None:
for emp in employee is not None:
print("k")
else:
print('Type is None')
If you look at the above example, there is a type check happening before iterating the variable, and that’s a more robust way to handle ‘nonetype
‘ errors in Python. Similarly, you could do a type check during concatenation or accessing the functions.