Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A method I cannot find in Python official documentation

Tags:

python

I was reading python cookbook and came upon this recipe:

If you have a slice instance s, you can get more information about it by looking at its s.start, s.stop, and s.step attributes, respectively. For example:

>>> a = slice(5, 50, 2)
>>> a.start
5
>>> a.stop
50
>>> a.step
2
>>>

In addition, you can map a slice onto a sequence of a specific size by using its indi ces(size) method. This returns a tuple (start, stop, step) where all values have been suitably limited to fit within bounds (as to avoid IndexError exceptions when indexing). For example:

>>> s = 'HelloWorld'
>>> a.indices(len(s))
(5, 10, 2)
>>> for i in range(*a.indices(len(s))):
... print(s[i])
...
W
r
d

I looked up indices() method in Python official documentation but couldn't find it. Is the book making a mistake here? If not, what does this method do?

like image 872
ChinaMahjongKing Avatar asked May 20 '26 23:05

ChinaMahjongKing


1 Answers

Calling help(a) on your initialized slice object, I found the following -

 |  indices(...)
 |      S.indices(len) -> (start, stop, stride)
 |
 |      Assuming a sequence of length len, calculate the start and stop
 |      indices, and the stride length of the extended slice described by
 |      S. Out of bounds indices are clipped in a manner consistent with the
 |      handling of normal slices.
like image 104
Harsh Avatar answered May 22 '26 13:05

Harsh