Typeerror nonetype object is not iterable

Typeerror nonetype object is not iterable : Complete Solution

Typeerror nonetype object is not iterable error occurs when we try to iterate any None type object. Actually, String, List, and tuple are iterable objects in python. We need to make sure that before iterating these objects must not be empty. In this article, We will see how we can avoid or fix this error with examples.

 

Typeerror nonetype object is not iterable : (Root Cause Example) –

 

Well, We before starting this section. Let’s replicate this error in a very easy way.

my_list=None
for ele in my_list:
  print(ele)

"<yoastmark

 

How to avoid this error (typeerror nonetype object is not iterable )?

The best way to avoid this error is to check the type of iterable object before each iteration.

my_list=None

if(type(my_list)!=None):
  print("object is None")
else:
  for ele in my_list:
    print(ele)

"<yoastmark

 

 

Handling nonetype object with try-except :

Well Ideally, We should avoid error while writing the code. But In some run time scenario we have to handle it. In that scenario, we can use the try-except over the code. This way we can plan the control over this unwanted situation( Nonetype object is not iterable).

my_list=None
try:
  for ele in my_list:
    print(ele)
except:
  print("This was an exception with None type object")
nonetype object is not iterable error handling
nonetype object is not iterable error handling

 

Real Scenario for nonetype object is not iterable :

appending a list :

It is very common as we all know that the append function returns nothing. But we do the code in the same way.

my_list=[1,2,3]
list_iter=my_list.append(4)
for ele in list_iter:
  print(ele)
nonetype object is not iterable error list
nonetype object is not iterable error list

In the above example, we can see that list _iter  is None because it holds the values after my_list.append(4) statement. As we have already mentioned that append returns None obj.

This was just to introduce you to a real scenario. There may be many more situations like this list append in tuple and string. But the root cause will always the same. Hence we need to follow the cycle avoidance and handler as mentioned above.

I hope this article will be your strong knowledge base for this error( nonetype object is not iterable). In case you have any queries, please comment below.

 

Thanks 

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner