Borislav Hadzhiev
Last updated: Apr 20, 2022
Check out my new book
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.
Here is an example of how the error occurs.
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.
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:
Name | Description |
---|---|
start | An integer representing the start of the range (defaults to 0 ) |
stop | Go up to, but not including the provided integer |
step | Range 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.
for n in range(5): print(n) result = list(range(5)) # 👇️ [0, 1, 2, 3, 4] print(result)
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.
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.
result = list(range(1, 0)) # 👇️ [] print(result)