Borislav Hadzhiev
Last updated: Apr 20, 2022
Check out my new book
The Python "TypeError: NoneType object does not support item assignment"
occurs when we try to perform an item assignment on a None
value. To solve the
error, figure out where the variable got assigned a None
value and correct the
assignment.
Here is an example of how the error occurs.
my_list = None # ⛔️ TypeError: 'NoneType' object does not support item assignment my_list[0] = 'a'
We tried to assign a value to a variable that stores None
.
None
value in your code and correct the assignment to a list or a dict.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(['a', 'b', 'c']) # 👇️ None my_list = get_list() # ⛔️ TypeError: 'NoneType' object does not support item assignment my_list[0] = 'z'
You can use the return
statement to return a value from a function.
def get_list(): return ['a', 'b', 'c'] # 👇️ ['a', 'b', 'c'] my_list = get_list() my_list[0] = 'z' print(my_list) # 👉️ ['z', 'b', 'c']
Use an if
statement if you need to check whether a variable doesn't store a
None
value before the assignment.
my_list = None if my_list is not None: my_list[0] = 'z' else: # 👇️ this runs print('variable stores a None value')
Alternatively, you can set a fallback value if the variable stores None
.
my_dict = None if my_dict is None: my_dict = {} my_dict['name'] = 'Alice' print(my_dict) # 👉️ {'name': 'Alice'}
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.
Another common cause of the error is having a function that returns a value only if a condition is met.
def get_list(a): if len(a) > 3: return a # 👇️ None my_list = get_list(['a', 'b'])
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 in this scenario, 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(a): if len(a) > 3: return a return [] # 👈️ return empty list if condition not met # 👇️ [] my_list = get_list(['a', 'b'])
Now the function is guaranteed to return a value regardless if the condition is met.