TypeError: 'range' object does not support item assignment

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

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

The Python "TypeError: 'range' object does not support item assignment" occurs when we try to change an item in a range object. To solve the error, convert the range object to a list before changing the value of the specific item.

typeerror range object does not support item assignment

Here is an example of how the error occurs.

main.py
my_range = range(5) print(my_range) # 👉️ range(0, 5) # ⛔️ TypeError: 'range' object does not support item assignment my_range[0] = 9

We tried updating the first value of a range object which caused the error.

To get around this, we can use the list() class to convert the range object into a list before changing the value for the item.

main.py
my_range = list(range(5)) print(my_range) # 👉️ [0, 1, 2, 3, 4] my_range[0] = 9 print(my_range) # 👉️ [9, 1, 2, 3, 4]

Range objects do not support item assignment but lists do, so converting the range into a list helps us get around this limitation.

The range class is commonly used for looping a specific number of times in for loops and takes the following parameters:

NameDescription
startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)

If you only pass a single argument to the range() constructor, it is considered to be the value for the stop parameter.

main.py
for n in range(5): print(n) result = list(range(5)) # 👇️ [0, 1, 2, 3, 4] print(result)
The example shows that if the start argument is omitted, it defaults to 0 and if the step argument is omitted, it defaults to 1.

If values for the start and stop parameters are provided, the start value is inclusive, whereas the stop value is exclusive.

main.py
result = list(range(1, 5)) # 👇️ [1, 2, 3, 4] print(result)

If the value for the stop parameter is lower than the value for the start parameter, the range will be empty.

main.py
result = list(range(1, 0)) # 👇️ [] print(result)
Use the search field on my Home Page to filter through my more than 3,000 articles.