TryBugHunt

TypeError: 'NoneType' object is not iterable

TypeError: 'NoneType' object is not iterable in Python means you looped over, unpacked, or passed to list() a value that is None. The function you expected to return a collection returned nothing.

PythonPattern: Null and undefined errors

How do I fix TypeError: 'NoneType' object is not iterable?

TypeError: 'NoneType' object is not iterable means you looped over, unpacked or passed None to list() or sum(). Most often the function that should build a list has no return statement, or returns nothing on one path. Add return result to the function, and return an empty list [] instead of None when nothing is found.

  1. 1. Print the iterated valuePrint the variable just before the for loop or unpacking line to confirm it is None.
  2. 2. Check the function returnsLook at every exit path of the function that produced it. Each one should return a list, even an empty one.
  3. 3. Look for in-place methodsa.extend(b), a.sort() and a.append(x) return None. Loop over a itself, not the method's result.

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

for, unpacking (a, b = ...), list(), sum(), max() and `in` all need an iterable. When the value is None the error appears at the loop, but the cause is wherever that None was created. Unpacking None gives the related message "cannot unpack non-iterable NoneType object".

Why does TypeError: 'NoneType' object is not iterable happen?

1. A function missing its return

The function builds the list perfectly and then never hands it back.

Breaks

def evens(nums):
    result = [n for n in nums if n % 2 == 0]

for n in evens([1, 2, 3, 4]):
    print(n)

Works

def evens(nums):
    return [n for n in nums if n % 2 == 0]

2. Unpacking from a function that sometimes returns None

A function returning a pair on success and nothing on failure breaks the caller's unpacking only on failure.

Breaks

def min_max(nums):
    if nums:
        return min(nums), max(nums)

lo, hi = min_max([])

Works

def min_max(nums):
    if not nums:
        return None, None
    return min(nums), max(nums)

3. Chaining off an in-place method

list.extend() returns None, so iterating over its result fails.

Breaks

for item in a.extend(b):
    print(item)

Works

a.extend(b)
for item in a:
    print(item)

How to find it in your own code

Find the variable being iterated and print it before the loop. If it is None, follow it back to the function that produced it and check every exit path returns a list — including the empty case. Returning [] instead of None for "nothing found" removes this whole class of crash.

Practise null and undefined errors

None of the challenges raises this exact error yet. These practise the same kind of bug.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.