What is :: (double colon) in Python when subscripting sequences?
seq[::n]
is a sequence of each n
-th item in the entire sequence.
Example:
>>> range(10)[::2]
[0, 2, 4, 6, 8]
The syntax is:
seq[start:end:step]
So you can do (in Python 2):
>>> range(100)[5:18:2]
[5, 7, 9, 11, 13, 15, 17]
Python sequence slice addresses can be written as a[start:end:step]
and any of start, stop or end can be dropped. a[::3]
is every third element of the sequence.
Explanation
s[i:j:k]
is, according to the documentation, "slice of s from i to j with step k". When i
and j
are absent, the whole sequence is assumed and thus s[::k]
means "every k-th item".
Examples
First, let's initialize a list:
>>> s = range(20)
>>> s
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Let's take every 3rd item from s
:
>>> s[::3]
[0, 3, 6, 9, 12, 15, 18]
Let's take every 3rd item from s[2:]
:
>>> s[2:]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> s[2::3]
[2, 5, 8, 11, 14, 17]
Let's take every 3rd item from s[5:12]
:
>>> s[5:12]
[5, 6, 7, 8, 9, 10, 11]
>>> s[5:12:3]
[5, 8, 11]
Let's take every 3rd item from s[:10]
:
>>> s[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> s[:10:3]
[0, 3, 6, 9]
it means 'nothing for the first argument, nothing for the second, and jump by three'. It gets every third item of the sequence sliced. Extended slices is what you want. New in Python 2.3