I need a good explanation (references are a plus) on Python slicing.
35 Answers
I don't think that the Python tutorial diagram (cited in various other answers) is good as this suggestion works for positive stride, but does not for a negative stride.
This is the diagram:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
From the diagram, I expect a[-4,-6,-1]
to be yP
but it is ty
.
>>> a = "Python"
>>> a[2:4:1] # as expected
'th'
>>> a[-4:-6:-1] # off by 1
'ty'
What always work is to think in characters or slots and use indexing as a half-open interval -- right-open if positive stride, left-open if negative stride.
This way, I can think of a[-4:-6:-1]
as a(-6,-4]
in interval terminology.
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
+---+---+---+---+---+---+---+---+---+---+---+---+
| P | y | t | h | o | n | P | y | t | h | o | n |
+---+---+---+---+---+---+---+---+---+---+---+---+
-6 -5 -4 -3 -2 -1 0 1 2 3 4 5
-
-
As a newbie, this is an interesting way of thinking about it. However, the last example, counting from -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 is a bit misleading because the string is NOT doubled like that. Furthermore, one can refer to the positive and negate positions like the following: a[-4:-6:-1] is the same as a[-4:0:-1] since the 0th position is the same as the -6th position. So I would just delete/ignore that example. Jan 9 at 5:22
I got a little frustrated in not finding an online source, or Python documentation that describes precisely what slicing does.
I took Aaron Hall's suggestion, read the relevant parts of the CPython source code, and wrote some Python code that performs slicing similarly to how it's done in CPython. I've tested my code in Python 3 on millions of random tests on integer lists.
You may find the references in my code to the relevant functions in CPython helpful.
def slicer(x, start=None, stop=None, step=None):
""" Return the result of slicing list x.
See the part of list_subscript() in listobject.c that pertains
to when the indexing item is a PySliceObject.
"""
# Handle slicing index values of None, and a step value of 0.
# See PySlice_Unpack() in sliceobject.c, which
# extracts start, stop, step from a PySliceObject.
maxint = 10000000 # A hack to simulate PY_SSIZE_T_MAX
if step is None:
step = 1
elif step == 0:
raise ValueError('slice step cannot be zero')
if start is None:
start = maxint if step < 0 else 0
if stop is None:
stop = -maxint if step < 0 else maxint
# Handle negative slice indexes and bad slice indexes.
# Compute number of elements in the slice as slice_length.
# See PySlice_AdjustIndices() in sliceobject.c
length = len(x)
slice_length = 0
if start < 0:
start += length
if start < 0:
start = -1 if step < 0 else 0
elif start >= length:
start = length - 1 if step < 0 else length
if stop < 0:
stop += length
if stop < 0:
stop = -1 if step < 0 else 0
elif stop > length:
stop = length - 1 if step < 0 else length
if step < 0:
if stop < start:
slice_length = (start - stop - 1) // (-step) + 1
else:
if start < stop:
slice_length = (stop - start - 1) // step + 1
# Cases of step = 1 and step != 1 are treated separately
if slice_length <= 0:
return []
elif step == 1:
# See list_slice() in listobject.c
result = []
for i in range(stop - start):
result.append(x[i+start])
return result
else:
result = []
cur = start
for i in range(slice_length):
result.append(x[cur])
cur += step
return result
-
I read all the relevant documents and found that there was no description of this syntax. I doubted my ability and felt relieved after seeing this answer. Maybe there was none.– AndyMar 26, 2021 at 23:22
It is easy to understand if we could relate slicing to range
, which gives the indexes. We can categorize slicing into the following two categories:
1. No step or step > 0. For example, [i:j]
or [i:j:k]
(k>0)
Suppose the sequence is s=[1,2,3,4,5]
.
- if
0<i<len(s)
and0<j<len(s)
, then[i:j:k] -> range(i,j,k)
For example, [0:3:2] -> range(0,3,2) -> 0, 2
- if
i>len(s)
orj>len(s)
, theni=len(s)
orj=len(s)
For example, [0:100:2] -> range(0,len(s),2) -> range(0,5,2) -> 0, 2, 4
- if
i<0
orj<0
, theni=max(0,len(s)+i)
orj=max(0,len(s)+j)
For example, [0:-3:2] -> range(0,len(s)-3,2) -> range(0,2,2) -> 0
For another example, [0:-1:2] -> range(0,len(s)-1,2) -> range(0,4,2) -> 0, 2
- if
i
is not specified, theni=0
For example, [:4:2] -> range(0,4,2) -> range(0,4,2) -> 0, 2
- if
j
is not specified, thenj=len(s)
For example, [0::2] -> range(0,len(s),2) -> range(0,5,2) -> 0, 2, 4
2. Step < 0. For example, [i:j:k]
(k<0)
Suppose the sequence is s=[1,2,3,4,5]
.
- if
0<i<len(s)
and0<j<len(s)
, then[i:j:k] -> range(i,j,k)
For example, [5:0:-2] -> range(5,0,-2) -> 5, 3, 1
- if
i>len(s)
orj>len(s)
, theni=len(s)-1
orj=len(s)-1
For example, [100:0:-2] -> range(len(s)-1,0,-2) -> range(4,0,-2) -> 4, 2
- if
i<0
orj<0
, theni=max(-1,len(s)+i)
orj=max(-1,len(s)+j)
For example, [-2:-10:-2] -> range(len(s)-2,-1,-2) -> range(3,-1,-2) -> 3, 1
- if
i
is not specified, theni=len(s)-1
For example, [:0:-2] -> range(len(s)-1,0,-2) -> range(4,0,-2) -> 4, 2
- if
j
is not specified, thenj=-1
For example, [2::-2] -> range(2,-1,-2) -> 2, 0
For another example, [::-1] -> range(len(s)-1,-1,-1) -> range(4,-1,-1) -> 4, 3, 2, 1, 0
In summary
The important idea to remember about indices of a sequence is that
- nonnegative indices begin at the first item in the sequence;
- negative indices begin at the last item in the sequence (so only apply to finite sequences).
In other words, negative indices are shifted right by the length of the sequence:
0 1 2 3 4 5 6 7 ...
-------------------------
| a | b | c | d | e | f |
-------------------------
... -8 -7 -6 -5 -4 -3 -2 -1
With that in mind, subscription and slicing are straightforward.
Subscription
Subscription uses the following syntax:*
sequence[index]
Subscription selects a single item in the sequence
at index
:
>>> 'abcdef'[0]
'a'
>>> 'abcdef'[-6]
'a'
Subscription raises an IndexError
for an index
that is out of range:
>>> 'abcdef'[100]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
Slicing
Slicing uses the following syntax:**
sequence[start:stop:step]
Slicing selects a range of items in the sequence
, beginning at start
inclusive and ending at stop
exclusive:
>>> 'abcdef'[0:2:1]
'ab'
>>> 'abcdef'[0:-4:1]
'ab'
>>> 'abcdef'[-6:-4:1]
'ab'
>>> 'abcdef'[-6:2:1]
'ab'
>>> 'abcdef'[1:-7:-1]
'ba'
>>> 'abcdef'[-5:-7:-1]
'ba'
Slicing defaults to the fullest range of items in the sequence
, so it uses the following default values for any start
, stop
, or step
that is omitted or equal to None
:***
step
defaults to1
;- if
step
is positivestart
defaults to0
(first item index),stop
defaults tostart + len(sequence)
(last item index plus one);
- if
step
is negativestart
defaults to-1
(last item index),stop
defaults tostart - len(sequence)
(first item index minus one).
>>> 'abcdef'[0:6:1]
'abcdef'
>>> 'abcdef'[::]
'abcdef'
>>> 'abcdef'[-1:-7:-1]
'fedcba'
>>> 'abcdef'[::-1]
'fedcba'
Slicing raises a ValueError
for a step
that is equal to zero:
>>> 'abcdef'[::0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: slice step cannot be zero
Slicing does not raise an IndexError
for a start
or stop
that is out of range (contrary to subscription):
>>> 'abcdef'[-100:100]
'abcdef'
* The expressions sequence[index]
and sequence.__getitem__(index)
are equivalent.
** The expressions sequence[start:stop:step]
, sequence[slice(start, stop, step)]
, and sequence.__getitem__(slice(start, stop, step))
are equivalent, where the built-in class slice
instance packs start
, stop
, and step
.
*** The expressions sequence[:]
, sequence[::]
, and sequence[None:None:None]
use default values for start
, stop
, and step
.
Lots of answers already, but I wanted to add a performance comparison
~$ python3.8 -m timeit -s 'fun = "this is fun;slicer = slice(0, 3)"' "fun_slice = fun[slicer]"
10000000 loops, best of 5: 29.8 nsec per loop
~$ python3.8 -m timeit -s 'fun = "this is fun"' "fun_slice = fun[0:3]"
10000000 loops, best of 5: 37.9 nsec per loop
~$ python3.8 -m timeit -s 'fun = "this is fun"' "fun_slice = fun[slice(0, 3)]"
5000000 loops, best of 5: 68.7 nsec per loop
~$ python3.8 -m timeit -s 'fun = "this is fun"' "slicer = slice(0, 3)"
5000000 loops, best of 5: 42.8 nsec per loop
So, if you are using the same slice repeatedly, it would be beneficial and improve readability to use a slice object. However, if you are slicing only a handful of times, [:] notation should be preferred.