Home > Net >  Why can't a range object be used to index a list?
Why can't a range object be used to index a list?

Time:01-25

In Python 3.9, it is not possible to use a range object to index a list. Indeed running the following code, the second print will return an error stating "TypeError: list indices must be integers or slices, not range".

x = [1, 2, 3]
s = slice(3)
r = range(3)

print(x[s]) # ok
print(x[r]) # error

Why is this? Couldn't the Python interpreter just convert the range to a slice under the hood, and use that for indexing? Is this because of some fundamental reason, or is just something the developer did not implement (yet?)?

Interestingly, it is indeed possible to index numpy arrays using range!

CodePudding user response:

range() is indeed not a list nor a tuple. It is not made for slicing.

It implements the class collections.abc.Sequence. It only saves in memory start, stop and step, which is great for memory management. The tradeoff here is that you cannot do all operations that you could do on lists, such as slicing. But you can easily convert a range() to a list like this : list(range(5)).

You might want to read further documentation here.

CodePudding user response:

Because range() creates a sequence of numbers to iterate. It's not made for slicing in any way.

range(5) == (0, 1, 2, 3, 4)   # not literally, just to iterate
  •  Tags:  
  • Related