Slicing in Sequence
The Pythonic convention of excluding the last item in slices and ranges works well with the zero-based indexing used in Python, C and many other languages.
# Given the list below
l = [10,20,30,40,50,60]
# index 0 1 2 3 4 5
print(l[:2]) # start at index 0, stop at index 2
>>> 10, 20
print(l[2:]) # start at index 2, no stop -> retrieve all, starting from index 2
>>> 30, 40, 50, 60
print(l[:3]) # start at index 0, no stop and step is 3: 0, 0+3, 3+3 etc.
>>> 10, 40
print(l[3::2]) # start at index 3, no stop and step is 2: 3, 3+2 etc.
>>> 40, 60
The stride/step can also be negative, returning items in reverse
s = "bicycle"
print(s[::3])
>>> 'bye'
print(s[::-1]) # negative step: bicycle -> elcycib
>>> 'elcycib'
print(s[::-2]) # negative step: bicycle -> elcycib, and step 2 -> eccb
>>> 'eccb'
# start at 3: bic<-y->cle
# No stop
# step in negative 2, ycib, index 0, 0+2, i.e. y then i
print(s[3::-2])
>>> 'yi'
# start at 5: bicyc<-l->e
# stop at 2: cycl
# step in negative 2 (reverse search and skip 2): cycl -> lcyc ->index 0, 0+2, ly
# step in negative 2, bic<-y, i.e. y then i
print(s[5:2:-2])
>>> 'ly'
The [ ]
operator can also take multiple indexes or slices separated by commas. The __getitem__
and __setitem__
special methods that handle the [] operator simply receive the indices in a[i, j] as a tuple. In other words, to evaluate a[i, j]
, Python calls a.__getitem__((i, j))
.
Multidimensional Slicing and Ellipsis
Last updated
Was this helpful?