209

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

for row in data:  # Gives TypeError!
    print(row)
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062
  • 4
    This is one of my annoying disappointments in Python. When `None` is coerced into as sequence it must produce an empty sequence, totally harmless. – nehem Sep 01 '17 at 06:56
  • 10
    @nehemiah: Python is strongly typed (just not statically typed). `None` is never coerced to *anything*. Having `None` silently behave like other types hides errors; that's the *opposite* of "harmless". If you need a falsy placeholder for the empty sequence, you can use `()` or `''`/`""`, both of which are singletons and can be loaded as cheaply as `None`. If you want to opt-in to silently treating anything falsy as an empty sequence, you could do `for row in data or ():`, but no one does that, because passing `None` to a function expecting a sequence is an error that shouldn't pass silently. – ShadowRanger Oct 05 '18 at 18:52
  • You may also get this error when in python 2 installing a module that no longer supports python 2, e.g. https://stackoverflow.com/q/63346648/838494 – Albert Hendriks Dec 31 '20 at 22:28
  • 2
    @nehem You must be a fan of Javascript. – Matt Yoon Jul 20 '21 at 08:42
  • @MattYoon JS got many things right. – nehem Jul 20 '21 at 12:36
  • @ShadowRanger that's an ugly excuse, if `str` can be happily considered as an iterable what's wrong in coercing None to be empty iterable, especially wherever the intention is clear. To make matters worse, lists and dict can be coerced as boolean, even strings too. The strongly typed didn't hold well for boolean. – nehem Aug 17 '21 at 03:02
  • I can't find this error in my project. – AnonymousUser Jun 11 '22 at 04:46
  • I found it today, it was in my function. The function never returned anything because of an if statement, now it does. See this https://stackoverflow.com/questions/59075266/nonetype-object-is-not-iterable-in-django-project – AnonymousUser Jun 12 '22 at 07:19

12 Answers12

265

It means the value of data is None.

Malekai
  • 4,765
  • 5
  • 25
  • 60
vanza
  • 9,715
  • 2
  • 31
  • 34
  • 68
    Correct, But the common scenario author intended here is totally to skip the `for` loop instead of raising an exception. Python's design is flawed here. When `None` is treated as an iterable it must return empty list at least. This exception never helped anyone in real life other than making us insert few ugly `if data is not None:` kind of handling. – nehem Sep 01 '17 at 06:59
  • For a more concrete answer, it can happen if the `fieldlist` for the `DictWriter` is `None`! – Arklur Dec 08 '17 at 16:53
  • 66
    Try `for i in data or []` – BMW Mar 27 '18 at 21:45
  • 9
    @nehemiah: Actually, the correct approach is not to check if `data` is or is not `None`, but to let the exception occur. You *want* the consumers of your API to know when they've used it incorrectly. Accepting `None` as an empty sequence would let mistakes like `mylist = mylist.extend(morestuff)`, manage to hide even longer; they think they `extend`ed a `list` (and they did, but then immediately replaced it with `None`), then pass it to the OP's function and wonder why the file is empty, with no errors raised of any kind. – ShadowRanger Oct 05 '18 at 18:56
  • 1
    @nehem Python's design is certainly not flawed. Stricter type systems make bugs much easier to find. cf. Rust, Haskell, Scala, et al. – Mateen Ulhaq Jun 06 '22 at 00:06
  • You do realize that Python is not strongly typed language, right,, At least be consistent everywhere instead of trying to be everything. – nehem Jun 06 '22 at 04:03
  • @nehem As others have said, Python is most definitely strongly typed. You have an example right here! Another is that e.g. 1+'0' and 1+None both (thankfully) result in an error. Maybe what you meant is that Python is not statically typed, that is true. – Arthur Tacca Nov 27 '22 at 17:49
  • @ArthurTacca I'm all for strongly typed as long as they are consistently enforced. Pythons design is not consistent. `bool(None) ` is okay but `list(None)` isn't it. Not so good. – nehem Nov 27 '22 at 22:11
  • @nehem In C++, `bool(nullptr)` is OK but `std::vector{nullptr}` is not. Does that mean that C++ is not strongly typed? Of course not. It's just that, in Python and C++ and lots of other strongly typed languages, lots more things are truthey/falsey that can be used as sequences. – Arthur Tacca Nov 28 '22 at 05:01
  • @ArthurTacca bringing cpp is not an ideal comparison. Python being a high level language converting between different types is essential in practicality. bool(None) is False, list(None) shud be [] and dict(None) shud be {} that's the clean design. – nehem Nov 28 '22 at 10:47
  • @nehem Ironically, what you're saying is that Python is *too strongly typed* for your preference! – Arthur Tacca Nov 29 '22 at 11:50
117

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.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
  • 2
    (a) Confuses `NoneType` and `None` (b) thinks that `NameError: name 'NoneType' is not defined` and `TypeError: cannot concatenate 'str' and 'NoneType' objects` are the same as `TypeError: 'NoneType' object is not iterable` (c) comparison between Python and java is "a bunch of unrelated nonsense" – John Machin Jan 07 '17 at 23:17
  • 4
    Umm... Java would have essentially identical problems if you passed `null` to a function expecting any collection type. C++ would have the same problem (but generally just die in a segfault without reporting the cause) for `nullptr` (admittedly, good C++ rarely uses pointers, but what you've demonstrated is bad Python, and bad C++ can die at runtime from nulls too). Python is doing the correct thing here; it's not "soldiering on", it's erroring out the moment you try to use `None` for anything `None` can't do. Your problem isn't with Python, it's with dynamically typed languages in general. – ShadowRanger Oct 05 '18 at 19:05
64

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?

John Machin
  • 81,303
  • 11
  • 141
  • 189
20

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"

gunslingor
  • 1,358
  • 12
  • 34
  • 3
    This is exactly what brought me here. So what's the Pythonic solution for such situation? – Dr_Zaszuś Oct 05 '18 at 09:45
  • 1
    It seems like there is some help here:https://stackoverflow.com/questions/1274875/returning-none-or-a-tuple-and-unpacking – Dr_Zaszuś Oct 05 '18 at 09:52
  • 1
    Dr_Zaszus that's exactly my question as well. This particular answer only says that there is indeed the problem. And, the accepted answer basically also just says "yes, this will throw an error". The entire thread is devoid of actual, good, accepted-practice answers to resolve the underlying problem. The best solution mentioned is in a comment, which is to add "if data is not None:", which is an ugly solution. – user3685427 Mar 24 '21 at 18:39
8

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.

Rod
  • 81
  • 1
  • 3
    it would be nice if just iterated like an empty list... would nake for cleaner code and less error checking – deltanine Aug 19 '13 at 01:03
  • 4
    @deltanine It would make for a lot of problems being more difficult to detect I think. I'm glad None is different from an empty iterable. If you want your described behaviour, just use `for row in data or []:` – Mark Dec 27 '14 at 18:32
  • @Mark it's lot cleaner if it returns empty list. If you want it to fail you can always add a line `if data is None: raise` – nehem Jul 20 '21 at 19:21
7

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.

clee
  • 10,943
  • 6
  • 36
  • 28
2

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.

JGFMK
  • 8,425
  • 4
  • 58
  • 92
1

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 "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable
  • Python 3.8
(a,b) = None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot unpack non-iterable NoneType object
Aman Gupta
  • 3,627
  • 4
  • 40
  • 64
0

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>
Pola Pola
  • 1
  • 1
0

i had this error with pandas in databricks.

The solution for this error was install the library in the cluster enter image description here

0

It means data is None, which is not an iterable. Adding an or []* prevents the exception and doesn't print anything:

for row in data or []:  # no more TypeError!
    print(row)

* credits to some earlier comments; please beware that raising an exception may be a desired behavior too and/or an indicator of improper data setting.

Ricardo
  • 3,696
  • 5
  • 36
  • 50
-3

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.

Sappaa
  • 1
  • 5