TypeError: argument of type 'NoneType' is not iterable [Fix] | bobbyhadz (2024)

# Table of Contents

  1. TypeError: argument of type 'NoneType' is not iterable
  2. TypeError: 'NoneType' object is not iterable in Python

# TypeError: argument of type 'NoneType' is not iterable

The Python "TypeError: argument of type 'NoneType' is not iterable" occurswhen we use the membership test operators (in and not in) with a None value.

To solve the error, correct the assignment of the variable that stores Noneor check if it doesn't store None.

TypeError: argument of type 'NoneType' is not iterable [Fix] | bobbyhadz (1)

Here is an example of how the error occurs.

main.py

Copied!

my_list = None# ⛔️ TypeError: argument of type 'NoneType' is not iterableprint('hello' in my_list)

We tried to use amembership test operatorwith a None value and got the error.

The code sample tries to check if the string hello is contained in thevariable.

# Checking if the variable is not None

One way to solve the error is tocheck if the variable is not None.

main.py

Copied!

my_list = Noneif my_list is not None and 'hello' in my_list: print('The string is contained in the list')else: print('The variable is None or the string is not in the list')

TypeError: argument of type 'NoneType' is not iterable [Fix] | bobbyhadz (2)

We used the and operator to check for 2 conditions.

The first condition checks that the values variable doesn't store a Nonevalue and the second condition checks if the string hello is contained in thevariable.

# Providing a default value if the variable is None

You can also assign a default value if a variable stores a None value.

main.py

Copied!

my_list = Noneif my_list is None: my_list = [] # 👈️ Set to an empty list if Noneprint('a' in my_list) # 👉️ False

TypeError: argument of type 'NoneType' is not iterable [Fix] | bobbyhadz (3)

We check if the my_list variable stores a None value and set it to an emptylist if it does.

You can also initialize the variable to an empty string if working with strings.

Alternatively, you can check if the variable is not None before you use thein or not in operators.

main.py

Copied!

my_list = Noneif my_list is not None: print('a' in my_list)else: # 👉️ this runs print('variable stores a None value')

The if block runs only if the variable doesn't store a None value,otherwise, the else block runs.

# Track down where the variable got assigned a None value

You have to track down where the variable got assigned a None value and eithercorrect the assignment or check if it doesn't store None before using in ornot in.

The most common sources of None values are:

  1. Having a function that doesn't return anything (returns None implicitly).
  2. Explicitly setting a variable to None.
  3. Assigning a variable to the result of calling a built-in function thatdoesn't return anything.
  4. Having a function that only returns a value if a certain condition is met.

# Functions that don't return anything return None

Make sure you don't have a function that doesn't return anything.

main.py

Copied!

# 👇️ This function returns Nonedef get_list(): print(['a', 'b', 'c'])# ⛔️ TypeError: argument of type 'NoneType' is not iterableprint('a' in get_list())

The get_list function doesn't explicitly return anything, so it implicitlyreturns None.

You can use a return statement toreturn a value from a function.

main.py

Copied!

def get_list(): print(['a', 'b', 'c']) return ['a', 'b', 'c']print('a' in get_list()) # 👉️ Trueprint('a' not in get_list()) # 👉️ False

TypeError: argument of type 'NoneType' is not iterable [Fix] | bobbyhadz (4)

We used a return statement to return a list from the function and use the inoperator correctly.

# Many built-in functions return None

Note that there are many built-in functions (like sort) that mutate an objectin place and therefore don't return a value(return None).

Make sure you're not assigning the result of calling one to a variable.

main.py

Copied!

my_list = ['c', 'b', 'a']result = my_list.sort()print(result) # 👉️ None# ⛔️ TypeError: argument of type 'NoneType' is not iterableprint('a' in result)

TypeError: argument of type 'NoneType' is not iterable [Fix] | bobbyhadz (5)

Instead of storing the result of sort in a variable, use the in operatorwith the original list.

main.py

Copied!

my_list = ['c', 'b', 'a']print('a' in my_list) # 👉️ True

# Functions that return a value only if a certain condition is met

Another common source of a None value is having a function that returns avalue only if a condition is met.

main.py

Copied!

def get_list(a): if len(a) > 3: return a# 👇️ Nonemy_list = get_list(['a', 'b'])# ⛔️ TypeError: argument of type 'NoneType' is not iterableprint('a' in my_list)

TypeError: argument of type 'NoneType' is not iterable [Fix] | bobbyhadz (6)

The if statement in the get_list function is only run if the passed-inargument has a length greater than 3.

In all other cases, the function doesn't return anything and ends up implicitly returning None.

To solve the error, you either have to check if the function didn't returnNone or return a default value if the condition isn't met.

main.py

Copied!

def get_list(a): if len(a) > 3: return a return [] # 👈️ Returns [] if condition not met# 👇️ Nonemy_list = get_list(['a', 'b'])print('a' in my_list) # 👉️ False

Now the function is guaranteed to return a value regardless of whether thecondition is met.

The in operator testsfor membership. For example, x in s evaluates to True if x is a member ofs, otherwise it evaluates to False.

main.py

Copied!

my_str = 'hello world'print('world' in my_str) # 👉️ Trueprint('another' in my_str) # 👉️ False

x not in s returns the negation of x in s.

All built-in sequences and set types support the in and not in operators.

When used with a dictionary, the operators check for the existence of the specified key in the dict object.

# TypeError: 'NoneType' object is not iterable in Python

The Python "TypeError: 'NoneType' object is not iterable" occurs when we tryto iterate over a None value.

To solve the error, figure out where the variable got assigned a None valueand correct the assignment or check if the variable doesn't store None beforeiterating.

TypeError: argument of type 'NoneType' is not iterable [Fix] | bobbyhadz (7)

Here is an example of how the error occurs.

main.py

Copied!

my_list = None# ⛔️ TypeError: 'NoneType' object is not iterablefor el in my_list: print(el)

We are trying to iterate over a None value and None is not iterable whichcauses the error.

# Checking if the variable is not None

Use an if statement if you need to check whether a variable doesn't store aNone value before iterating.

main.py

Copied!

my_list = Noneif my_list is not None: for i in my_list: print(i)else: # 👇️ this runs print('variable stores a None value')

Alternatively, you can provide an empty list as a fallback.

main.py

Copied!

my_list = Nonefor i in my_list or []: print(i)

If the my_list variable stores a None value, we provide a fallback of anempty list to avoid getting the error.

You can also assign a fallback value to a variable if it stores a None value.

main.py

Copied!

my_list = Noneif my_list is None: my_list = []else: for i in my_list: print(i)

If the variable stores a None value, we initialize it to an empty list,otherwise, we use a for loop to iterate overit.

# The most common sources of None in Python

The most common sources of None values are:

  1. Having a function that doesn't return anything (returns None implicitly).
  2. Explicitly setting a variable to None.
  3. Assigning a variable to the result of calling a built-in function thatdoesn't return anything.
  4. Having a function that only returns a value if a certain condition is met.

# Functions that don't return a value return None

Functions that don't explicitly return a value return None.

main.py

Copied!

# 👇️ this function returns Nonedef get_list(): print(['a', 'b', 'c'])# 👇️ Nonemy_list = get_list()# ⛔️ TypeError: 'NoneType' object is not iterablefor el in my_list: print(el)

You can use a return statement to return a value from a function.

main.py

Copied!

def get_list(): return ['a', 'b', 'c'] # 👈️ return value# 👇️ ['a', 'b', 'c']my_list = get_list()for el in my_list: print(el) # 👉️ a, b, c

The function now returns a list instead of None, so we are able to iterateover the result.

# Many built-in methods return None in Python

Note that there are many built-in functions (e.g. sort()) that mutate theoriginal object in place and return None.

main.py

Copied!

my_list = ['c', 'b', 'a']new_list = my_list.sort()print(new_list) # 👉️ Nonefor i in new_list: # ⛔️ TypeError: 'NoneType' object is not iterable print(i)

The sort() method returns None, so we shouldn't store the result of callingit into a variable.

Instead, call the method on the list and iterate over the original list after ithas been sorted.

main.py

Copied!

my_list = ['c', 'b', 'a']my_list.sort()for i in my_list: print(i) # 👉️ a b c

Make sure you aren't storing the result of calling a built-in method thatreturns None in a variable.

# Functions that return value only if a condition is met

Another common cause of the error is having a function that returns a value onlyif a condition is met.

main.py

Copied!

def get_list(a): if len(a) > 3: return a# 👇️ Nonemy_list = get_list(['a', 'b'])# ⛔️ TypeError: 'NoneType' object is not iterablefor i in my_list: print(i)

The if statement in the get_list function is only run if the passed-inargument has a length greater than 3.

In all other cases, the function doesn't return anything and ends up implicitly returning None.

To solve the error, you either have to check if the function didn't returnNone, or return a default value if the condition is not met.

main.py

Copied!

def get_list(a): if len(a) > 3: return a return [] # 👈️ Return an empty list if the condition is not met# 👇️ []my_list = get_list(['a', 'b'])for i in my_list: print(i)

Now the function is guaranteed to return a value regardless of whether thecondition is met.

# Checking if an object is iterable

If you need tocheck if an object is iterable, usea try/except statement.

main.py

Copied!

my_str = 'hello'try: my_iterator = iter(my_str) for i in my_iterator: print(i) # 👉️ h, e, l, l, oexcept TypeError as te: print(te)

The iter() function raises aTypeError if the passed-in value doesn't support the __iter__() method orthe sequence protocol (the __getitem__() method).

If we pass a non-iterable object like a None value to the iter() function,the except block is run.

main.py

Copied!

my_list = Nonetry: my_iterator = iter(my_list) for i in my_iterator: print(i)except TypeError as te: print(te) # 👉️ 'NoneType' object is not iterable

Examples of iterables include all sequence types (list, str, tuple) andsome non-sequence types like dict, file objects and other objects that definean __iter__() or a __getitem__() method.

TypeError: argument of type 'NoneType' is not iterable [Fix] | bobbyhadz (2024)

References

Top Articles
Latest Posts
Article information

Author: Sen. Ignacio Ratke

Last Updated:

Views: 6475

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Sen. Ignacio Ratke

Birthday: 1999-05-27

Address: Apt. 171 8116 Bailey Via, Roberthaven, GA 58289

Phone: +2585395768220

Job: Lead Liaison

Hobby: Lockpicking, LARPing, Lego building, Lapidary, Macrame, Book restoration, Bodybuilding

Introduction: My name is Sen. Ignacio Ratke, I am a adventurous, zealous, outstanding, agreeable, precious, excited, gifted person who loves writing and wants to share my knowledge and understanding with you.