Typeerror Argument Of Type Nonetype Is Not Iterable

5 min read

TypeError: Argument of Type 'NoneType' Is Not Iterable — Causes, Fixes, and Prevention

The error TypeError: argument of type 'NoneType' is not iterable is one of the most common runtime errors Python developers encounter, and it almost always points to a single root cause: you tried to run a membership test (in or not in) against a value that is None. This guide explains exactly what Python is complaining about, why None breaks the in operator, the ten or so situations that produce this error most often, and how to fix it permanently rather than patching it with try/except blocks And that's really what it comes down to..

This changes depending on context. Keep that in mind.

What the Error Actually Means

In Python, the expression x in y is shorthand for asking a question: does the container y contain the item x? To answer that question, Python needs y to be something it can search. Under the hood, Python looks for one of two things on the object:

  • A __contains__ method (the membership protocol), or
  • An __iter__ method (the iteration protocol), which Python can fall back on by looping through the object.

Lists, tuples, sets, dictionaries, strings, and generators all support this. Also, the None object does not. None is a singleton of the NoneType class, and NoneType implements neither __contains__ nor __iter__ And that's really what it comes down to. Less friction, more output..

>>> "admin" in None
TypeError: argument of type 'NoneType' is not iterable

Notice the wording carefully. The error says the argument — the right-hand side of in — is not iterable. On top of that, it is not saying your left-hand value is wrong. The bug is almost never in the item you are searching for; it is in the container you assumed existed Practical, not theoretical..

Why None Is Different From an Empty Container

A frequent point of confusion is why an empty list is fine but None is not:

"admin" in []      # Valid → returns False
"admin" in None    # TypeError

An empty list is a real container that simply holds nothing. Also, None represents the absence of a value entirely. Python has no idea whether None was meant to be a list, a string, or a dictionary, so it cannot guess how to search it. This distinction — empty versus absent — is the conceptual key to the whole error That's the part that actually makes a difference..

The Most Common Causes

1. A Function With No return Statement

Any Python function that finishes without hitting a return implicitly returns None. This is the single most frequent source of the error.

def get_users():
    users = ["alice", "bob"]
    users.append("charlie")   # Forgot to return anything

if "alice" in get_users():    # TypeError
    print("found")

The fix is trivial once you see it: add return users And that's really what it comes down to. No workaround needed..

2. dict.get() on a Missing Key

dict.get() returns None by default instead of raising KeyError, which makes it easy to lose track of:

config = {"debug": True}
roles = config.get("roles")     # None, key does not exist

if "editor" in roles:           # TypeError
    ...

Use the second argument to supply a safe default:

roles = config.get("roles", [])

3. Regular Expression Results

re.match() and re.search() return a match object when they find something and None when they do not.

match = re.search(r"\d+", "no digits here")   # None

if "5" in match.group(0):     # AttributeError first, TypeError if misused

Always check the match before using it:

match = re.search(r"\d+", text)
if match and "5" in match.group(0):
    ...

4. Methods That Return None by Design

Several built-in methods mutate an object in place and return None. Assigning their result destroys your data:

numbers = [3, 1, 2]
numbers = numbers.sort()      # numbers is now None

if 2 in numbers:              # TypeError
    ...

The same trap applies to list.update(), and set.add(). append(), list.reverse(), list.insert(), dict.Call them for their side effect, and keep using the original variable Simple as that..

5. Variables Initialized to None and Never Populated

A very common pattern in application code:

class Cart:
    def __init__(self):
        self.items = None       # Should be []

    def add(self, item):
        if item in self.items:  # TypeError on first call
            return
        self.items.

Initialize collections to empty containers, not `None`. Reserve `None` for genuinely optional values.

### 6. Missing Data From APIs, Databases, or JSON

External data is full of `null`. When `null` is deserialized into Python, it becomes `None`:

```python
payload = {"user": {"name": "Ada", "roles": None}}

if "admin" in payload["user"]["roles"]:   # TypeError

Validate the shape of external data before using it. A schema validator or a simple guard clause both work.

7. Conditional Logic That Skips Assignment

tags = None
if request.method == "POST":
    tags = request.form.getlist("tags")

if "urgent" in tags:      # TypeError on GET requests

Here tags is None whenever the branch does not run. Initialize it to [] instead, or guard the membership test with if tags and "urgent" in tags Surprisingly effective..

8. Shadowing a Built-in or Reusing a Name

Reassigning a variable to None in one branch of a loop and forgetting it exists in the next iteration produces intermittent, hard-to-reproduce failures. These are the worst kind, because the code works on the happy path and breaks only for specific inputs.

How to Debug It in Under a Minute

Work through these steps in order:

  1. Read the traceback bottom-up. The last frame in your own code is the exact line that failed. Ignore library frames above it.
  2. **Identify the right-hand side of in
This Week's New Stuff

Freshest Posts

On a Similar Note

Related Corners of the Blog

Thank you for reading about Typeerror Argument Of Type Nonetype Is Not Iterable. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home