TypeError: 'NoneType' object is not iterable in Python

Viewed 908430

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

for row in data:  # Gives TypeError!
    print(row)
11 Answers

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.

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

This means that the value of data is None.

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>

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.

Related