TypeError: 'type' object does not support item assignment

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

TypeError: 'type' object does not support item assignment #

The Python "TypeError: 'type' object does not support item assignment" occurs when we assign a data type to a variable and use square brackets to change an index or a key. To solve the error, set the variable to a mutable container object, e.g. my_list = [].

typeerror type object does not support item assignment

Here are 2 examples of how the error occurs.

main.py
my_list = list # ⛔️ TypeError: 'type' object does not support item assignment my_list[0] = 'apple' # --------------------------------------------------------------- my_dict = dict # ⛔️ TypeError: 'type' object does not support item assignment my_dict['name'] = 'Alice'

In the first example, we declared a my_list variable and set its value to a list class instead of a mutable list object.

To solve the error, make sure to assign the correct value to your variable.

main.py
my_list = ['a', 'b', 'c'] my_list[0] = 'apple' # 👇️ add item to the end of a list my_list.append('melon') # 👇️ insert item at specific index my_list.insert(0, 'avocado') print(my_list) # 👉️ ['avocado', 'apple', 'b', 'c', 'melon']

You could also use the built-in class to declare a list but you'd have to call it with parenthesis.

main.py
# 👇️ call list() class my_list = list(['a', 'b', 'c']) my_list[0] = 'apple' # 👇️ add item to the end of a list my_list.append('melon') # 👇️ insert item at specific index my_list.insert(0, 'avocado') print(my_list) # 👉️ ['avocado', 'apple', 'b', 'c', 'melon']

The same is the case with any other built-in type.

main.py
# 👇️ call built-in dict class my_dict = dict() my_dict['name'] = 'Alice' print(my_dict) # 👉️ {'name': 'Alice'}

We called the dict() class to create a dictionary before we set any key-value pairs.

Alternatively, you could have used curly braces, which is the more common way a dictionary is created.

main.py
my_dict = {} my_dict['name'] = 'Alice' print(my_dict) # 👉️ {'name': 'Alice'}

You can use the type() function to look at the difference of declaring a variable and setting it to dict or setting it to dict().

main.py
print(type(dict)) # 👉️ <class 'type'> print(type(dict())) # 👉️ <class 'dict'>

The type class returns the type of an object.

Most commonly the return value is the same as accessing the __class__ attribute on the object.

The first example assigns the variable to an object of type type, whereas the second creates a dictionary.

Make sure you aren't overriding the values of any of the built-in objects, e.g. list, dict, tuple, str, etc, by declaring variables with those names as that could lead to very confusing and difficult to debug behavior.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.