TypeError: 'NoneType' object is not iterable in Python

PythonNonetype

Python Problem Overview


What does error TypeError: 'NoneType' object is not iterable mean?

I am getting it on this Python code:

def write_file(data, filename): # creates file and writes list to it
  with open(filename, 'wb') as outfile:
    writer = csv.writer(outfile)
    for row in data: # ABOVE ERROR IS THROWN HERE
      writer.writerow(row)

Python Solutions


Solution 1 - Python

It means the value of data is None.

Solution 2 - Python

Explanation of error: 'NoneType' object is not iterable

In python2, NoneType is the type of None. In Python3 NoneType is the class of None, for example:

>>> print(type(None))     #Python2
<type 'NoneType'>         #In Python2 the type of None is the 'NoneType' type.

>>> print(type(None))     #Python3
<class 'NoneType'>        #In Python3, the type of None is the 'NoneType' class.

Iterating over a variable that has value None fails:

for a in None:
    print("k")     #TypeError: 'NoneType' object is not iterable

Python methods return NoneType if they don't return a value:

def foo():
    print("k")
a, b = foo()      #TypeError: 'NoneType' object is not iterable

You need to check your looping constructs for NoneType like this:

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 only use is to check for None because is is more robust to identity checking. Don't use equality operations because those can spit bubble-up implementationitis of their own. Python's Coding Style Guidelines - PEP-008

NoneTypes are Sneaky, and can sneak in from lambdas:

import sys
b = lambda x : sys.stdout.write("k") 
for a in b(10): 
    pass            #TypeError: 'NoneType' object is not iterable 

NoneType is not a valid keyword:

a = NoneType     #NameError: name 'NoneType' is not defined

Concatenation of None and a string:

bar = "something"
foo = None
print foo + bar    #TypeError: cannot concatenate 'str' and 'NoneType' objects

What's going on here?

Python's interpreter converted your code to pyc bytecode. The Python virtual machine processed the bytecode, it encountered a looping construct which said iterate over a variable containing None. The operation was performed by invoking the __iter__ method on the None.

None has no __iter__ method defined, so Python's virtual machine tells you what it sees: that NoneType has no __iter__ method.

This is why Python's duck-typing ideology is considered bad. The programmer does something completely reasonable with a variable and at runtime it gets contaminated by None, the python virtual machine attempts to soldier on, and pukes up a bunch of unrelated nonsense all over the carpet.

Java or C++ doesn't have these problems because such a program wouldn't be allowed to compile since you haven't defined what to do when None occurs. Python gives the programmer lots of rope to hang himself by allowing you to do lots of things that should cannot be expected to work under exceptional circumstances. Python is a yes-man, saying yes-sir when it out to be stopping you from harming yourself, like Java and C++ does.

Solution 3 - Python

Code: for row in data:
Error message: TypeError: 'NoneType' object is not iterable

Which object is it complaining about? Choice of two, row and data. In for row in data, which needs to be iterable? Only data.

What's the problem with data? Its type is NoneType. Only None has type NoneType. So data is None.

You can verify this in an IDE, or by inserting e.g. print "data is", repr(data) before the for statement, and re-running.

Think about what you need to do next: How should "no data" be represented? Do we write an empty file? Do we raise an exception or log a warning or keep silent?

Solution 4 - Python

Another thing that can produce this error is when you are setting something equal to the return from a function, but forgot to actually return anything.

Example:

def foo(dict_of_dicts):
    for key, row in dict_of_dicts.items():
        for key, inner_row in row.items():
            Do SomeThing
    #Whoops, forgot to return all my stuff

return1, return2, return3 = foo(dict_of_dicts)

This is a little bit of a tough error to spot because the error can also be produced if the row variable happens to be None on one of the iterations. The way to spot it is that the trace fails on the last line and not inside the function.

If your only returning one variable from a function, I am not sure if the error would be produced... I suspect error "'NoneType' object is not iterable in Python" in this case is actually implying "Hey, I'm trying to iterate over the return values to assign them to these three variables in order but I'm only getting None to iterate over"

Solution 5 - Python

It means that the data variable is passing None (which is type NoneType), its equivalent for nothing. So it can't be iterable as a list, as you are trying to do.

Solution 6 - Python

You're calling write_file with arguments like this:

write_file(foo, bar)

But you haven't defined 'foo' correctly, or you have a typo in your code so that it's creating a new empty variable and passing it in.

Solution 7 - Python

For me it was a case of having my Groovy hat on instead of the Python 3 one.

Forgot the return keyword at the end of a def function.

Had not been coding Python 3 in earnest for a couple of months. Was thinking last statement evaluated in routine was being returned per the Groovy (or Rust) way.

Took a few iterations, looking at the stack trace, inserting try: ... except TypeError: ... block debugging/stepping thru code to figure out what was wrong.

The solution for the message certainly did not make the error jump out at me.

Solution 8 - Python

It also depends on Python version you are using. Seeing different error message thrown in python 3.6 and python 3.8 as following which was the issue in my case

  • Python 3.6

> (a,b) = None > Traceback (most recent call last): > File "", line 1, in > TypeError: 'NoneType' object is not iterable

  • Python 3.8

> (a,b) = None > Traceback (most recent call last): > File "", line 1, in > TypeError: cannot unpack non-iterable NoneType object

Solution 9 - Python

This means that the value of data is None.

Solution 10 - Python

because using for loop while the result it is just one value not a set of value

> pola.py

@app.route("/search")
def search():
    title='search'
    search_name =  request.form.get('search')
    
    search_item =   User.query.filter_by(id=search_name).first()

    return render_template('search.html', title=title, search_item=search_item  ) 

> search.html (wrong)

{% for p in search %}
{{ p }}

> > search.html (correct)

<td>{{ search_item  }}</td>

Solution 11 - Python

Just continue the loop when you get None Exception,

example:

   a = None
   if a is None:
       continue
   else:
       print("do something")

This can be any iterable coming from DB or an excel file.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex GordonView Question on Stackoverflow
Solution 1 - PythonvanzaView Answer on Stackoverflow
Solution 2 - PythonEric LeschinskiView Answer on Stackoverflow
Solution 3 - PythonJohn MachinView Answer on Stackoverflow
Solution 4 - PythongunslingorView Answer on Stackoverflow
Solution 5 - PythonRodView Answer on Stackoverflow
Solution 6 - PythoncleeView Answer on Stackoverflow
Solution 7 - PythonJGFMKView Answer on Stackoverflow
Solution 8 - PythonAman GuptaView Answer on Stackoverflow
Solution 9 - PythonMy CarView Answer on Stackoverflow
Solution 10 - PythonPola PolaView Answer on Stackoverflow
Solution 11 - PythonSappaaView Answer on Stackoverflow