Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
The Python "TypeError: cannot unpack non-iterable NoneType object" occurs when
we try to unpack a None
value. To solve the error, track down where the
variable got assigned a None value and correct the assignment to an iterable,
e.g. a list or a tuple.
Here is an example of how the error occurs.
# ⛔️ TypeError: cannot unpack non-iterable NoneType object a, b = None
We are trying to unpack a None
value, but None
values are not iterable.
If you need to declare multiple variables that store None
on the same line,
separate multiple None
values by commas.
a, b = None, None print(a) # 👉️ None print(b) # 👉️ None
None
value and correct the assignment.The most common sources of None
values are:
None
implicitly).None
.Functions that don't explicitly return a value return None
.
# 👇️ this function returns None def get_list(): print(['one', 'two']) # ⛔️ TypeError: cannot unpack non-iterable NoneType object a, b = get_list()
You can use a return
statement to return a value from a function.
def get_list(): return ['one', 'two'] a, b = get_list() print(a) # 👉️ 'one' print(b) # 👉️ 'two'
Use an if
statement if you need to check whether a variable doesn't store a
None
value before unpacking it.
example = None if example is not None: a, b = example else: # 👇️ this runs print('variable stores a None value')
sort()
) that mutate the original object in place and return None
.Make sure you aren't storing the result of calling one in a variable.
my_list = ['c', 'b', 'a'] # ⛔️ TypeError: cannot unpack non-iterable NoneType object x, y, z = my_list.sort()
The sort
functions and many other built-in functions return None
because
they mutate the original object.
Another common cause of the error is having a function that returns a value only if a condition is met.
def get_list(l): if len(l) > 3: return l my_list = get_list(['one', 'two', 'three']) print(my_list) # 👉️ None # ⛔️ TypeError: cannot unpack non-iterable NoneType object a, b, c = my_list
The if
statement in the get_list
function is only ran if the passed in
argument has a length greater than 3
.
None
.To solve the error, you either have to check if the function didn't return
None
, or return a default value if the condition is not met.
def get_list(l): if len(l) > 3: return l return ['', '', ''] # 👈️ return default value if condition not met my_list = get_list(['one', 'two', 'three']) print(my_list) # 👉️ ['', '', ''] a, b, c = my_list print(a, b, c) # 👉️ "", "", ""
Now the function is guaranteed to return a value regardless if the condition is met.