Basic index slicing Link to heading

python defines slicing with [start:stop:step] to access elements of sequences(list, seq, str).

>>> x = list(range(10))
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x[1:8:2]
[1, 3, 5, 7]
>>> x[:3]
[0, 1, 2]
>>> x[5:]
[5, 6, 7, 8, 9]

Named slice Link to heading

for readability, index range can be names with slice object and used to index sequences.


>>> mid = slice(3,9,2)
>>> mid
slice(3, 9, 2)
>>> sel = x[mid]
>>> sel
[3, 5, 7]

Slice in python model Link to heading

To support slicing in user defined class, class needs to have __getitem__


In [4]: class List:
   ...:     def __init__(self):
   ...:         self.x = list(range(10))
   ...:     def __getitem__(self, i):
   ...:         return self.x[i]
   ...:

In [5]: l = List()

In [6]: l[2]
Out[6]: 2