Slices in Python

by: George El., February 2019, Reading time: 1 minute

With Slices we can take a slice (sub section) of any sequence, like lists and tuples. The syntax is

slice(stop)
slice(start, stop, step)

but we can shorten it to

nameofsequence(start:stop:step)

where

  • start - starting integer where the slicing of the object starts (optional, 0 is default)
  • stop - integer where the slicing stops. It is not inclusive of stop. The slicing ends at stop-1 (optional, last index is default)
  • step - integer which determines the increment between each index for slicing (optional, 1 is default)

Lets move to some examples

>>> l = [0,1,2,3,4,5]
>>> l[0:2]
[0, 1]
>>> l[0:5]
[0, 1, 2, 3, 4]

The stop index is not inclusive. Also we can ommit either the start or the stop index

>>> l[:3]
[0, 1, 2]
>>> l[2:]
[2, 3, 4, 5]

if we ommit both we get the whole list.

>>> l[:]
[0, 1, 2, 3, 4, 5]

The step can be positive or negative. With negative -1 we get the reverse list

>>> l[::2]
[0, 2, 4]
>>> l[::-2]
[5, 3, 1]
>>> l[::-1]
[5, 4, 3, 2, 1, 0]

Strings are also sequences, so we can slice strings too

>>> str[0:2]
'AB'
>>> str[-2:]
'DE'
>>> str[::2]
'ACE'
>>> str[::-1]
'EDCBA'
comments powered by Disqus