How To Solve TypeError: ‘type’ object does not support item assignment in Python

Some situations in the working process make you forced to assign the data type to a variable. Sometimes there will be a TypeError: ‘type’ object does not support item assignment error. This article will show the cause of the error and some ways to fix it. Let’s start.

What causes the error TypeError: ‘type’ object does not support item assignment

An error occurs when you change the value at an index of a variable assigned by the data type. The variable is only accessible when using the index of a mutable collection of objects. If you try to add the value at that index, the TypeError: ‘type’ object does not support item assignment will appear.

Error example:

# Assign data type List to variable cart
cart = list

# Assign some items to index 0 of the list cart
cart[0] = "some item"
print(cart)

Output:

TypeError: 'type' object does not support item assignment

Variables in Python can be used to store the data type. The value at the index position of this variable cannot be assigned data using the “=” operator.

Solutions for TypeError: ‘type’ object does not support item assignment.

Pass in a collection

The cause of the error is missing a value while assigning to the variable. So you pass in a collection, and the error is resolved.

Example:

items = ("food", "medicine", "water")

# Pass in a collection
cart = list(items)

# Assign new item at index 0
cart[0] = "cosmetics"
print(cart)

Output:

['cosmetics', 'medicine', 'water']

Use the insert() function

Create an empty List, then use the insert() function to add data to the List.

Syntax:

list.insert(index, value)

Parameters:

index: is the index position where the value will be added
value: this is the value that will be added to the index position

Return Value:

This function does not return anything.

Example:

cart = list()

# Use the insert() function to add data to the List
cart.insert(0, "medicine")
print(cart)

Output:

['medicine']

Store variable data types in a list

Create a list containing the data types, and assign the data type to the List index position.

Example:

# Create a list containing the data types
cart = [list] * 10

# Assign the data type to the List index position
cart[0] = dict
print(cart)

Output:

[<class 'dict'>, <class 'list'>, <class 'list'>, <class 'list'>, <class 'list'>, <class 'list'>, <class 'list'>, <class 'list'>, <class 'list'>, <class 'list'>]

You can learn more about some other common errors in this article.

Summary

So the TypeError: ‘type’ object does not support item assignment has been fixed quickly by using some alternative ways. Hope the article is helpful to you. Good luck.

Leave a Reply

Your email address will not be published. Required fields are marked *