What is the point of the slice.indices
method, since we have the following equality?
s = slice(start, stop, step)
assert range(*s.indices(length)) == range(length)[s]
Since Python 3.2 added slicing support to range
, the slice.indices
method is unnecessary because s.indices(length)
is equal to (range(length)[s].start, range(length)[s].stop, range(length)[s].step)
:
range
objects now support index and count methods. This is part of an effort to make more objects fully implement thecollections.Sequence
abstract base class. As a result, the language will have a more uniform API. In addition,range
objects now support slicing and negative indices, even with values larger thansys.maxsize
. This makes range more interoperable with lists:>>> range(0, 100, 2).count(10) 1 >>> range(0, 100, 2).index(10) 5 >>> range(0, 100, 2)[5] 10 >>> range(0, 100, 2)[0:5] range(0, 10, 2)
(Contributed by Daniel Stutzbach in bpo-9213, by Alexander Belopolsky in bpo-2690, and by Nick Coghlan in bpo-10889.)
The slice.indices
method is only kept for backwards compatibility.
The credit goes to Karl Knechtel.