Slicing in Python
Slicing in Python
Is It?
***
>>> str_[-1]
'!'
>>> str_[-2]
'e'
>>> str_[-5]
's'
>>> tuple_[-1]
128
>>> tuple_[-2]
64
>>> tuple_[-5]
8
>>> list_[-1]
128
>>> list_[-2]
64
>>> list_[-5]
8
>>> str_[1:5]
'ytho'
>>> tuple_[2:4]
(4, 8)
>>> tuple_[2:3]
(4,)
>>> tuple_[2:2]
()
As you can see, the returning sequence
can contain only one item when start + 1
== stop or it can be an empty sequence
when start == stop.
>>> str_[:2]
'Py'
>>> tuple_[:4]
(1, 2, 4, 8)
>>> str_[2:]
'thon is awesome!'
>>> tuple_[4:]
(16, 32, 64, 128)
>>> str_[:]
'Python is awesome!'
>>> tuple_[:]
(1, 2, 4, 8, 16, 32, 64, 128)
>>> list_[:]
[1, 2, 4, 8, 16, 32, 64, 100]
That’s how you get a shallow copy of a
sequence.
It’s possible to apply negative values of
start and stop similarly as with indices:
>>> str_[-8:]
'awesome!'
>>> tuple_[:-1]
(1, 2, 4, 8, 16, 32, 64)
>>> tuple_[-4:-2]
(8, 16)
>>> tuple_[3:5]
(8, 16)
>>> tuple_[1:5:2]
(2, 8)
>>> tuple_[:6:2]
(1, 4, 16)
>>> tuple_[3::2]
(8, 32, 128)
>>> tuple_[1:5:]
(2, 4, 8, 16)
>>> tuple_[4:1:-1]
(16, 8, 4)
>>> tuple_[6:1:-2]
(64, 16, 4)
In the cases with negative step and
omitted start, the resulting sequence
starts at the end of the original.
>>> tuple_[:2:-1]
(128, 64, 32, 16, 8)
>>> tuple_[5::-1]
(32, 16, 8, 4, 2, 1)
>>> tuple_[::-1]
(128, 64, 32, 16, 8, 4, 2, 1)
>>> list_[1:6:2]
[2, 8, 32]
>>> list_[1:6:2] = [20, 80, 320]
>>> list_
[1, 20, 4, 80, 16, 320, 64, 100]
>>> list_[1:5]
[20, 4, 80, 16]
>>> list_[1:5] = [0, 0]
>>> list_
[1, 0, 0, 320, 64, 100]
>>> list_[1:3]
[0, 0]
>>> list_[1:3] = []
>>> list_
[1, 320, 64, 100]
>>> list_[:2]
[1, 320]
>>> del list_[:2]
>>> list_
[64, 100]
>>> s = slice(1, 5, 2)
>>> s
slice(1, 5, 2)
>>> s.start, s.stop, s.step
(1, 5, 2)
>>> tuple_[s]
(2, 8)
>>> s = slice(1, 5)
>>> s.start, s.stop, s.step
(1, 5, None)
>>> tuple_[s]
(2, 4, 8, 16)
>>> s = slice(5)
>>> s.start, s.stop, s.step
(None, 5, None)
>>> tuple_[s]
(1, 2, 4, 8, 16)
>>> class C:
... def __init__(self, *args):
... self.__data = args
... def __getitem__(self, index_or_slice):
... print('index or slice:',
index_or_slice)
... return self.__data[index_or_slice]
...
>>> x = C(1, 2, 4, 8, 16, 32, 128)
>>> x[4]
index or slice: 4
16
>>> x[1:5:2]
index or slice: slice(1, 5, 2)
(2, 8)
Table of contents:
• Indexing
• Slicing
• What Are Slices?
• Conclusions