I know I can use something like string[3:4] to get a substring in Python, but what is the is something[::3]?
Sorry but it's hard to search for this on Google.
I know I can use something like string[3:4] to get a substring in Python, but what is the is something[::3]?
Sorry but it's hard to search for this on Google.
When slicing in Python the third parameter is the step. As others mentioned, see Extended Slices for a nice overview.
With this knowledge, [::3]
just means that you have not specified any start or end indices for your slice. Since you have specified a step, 3
, this will take every third entry of something
starting at the first index. For example:
>>> '123123123'[::3]
'111'
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 array.
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
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:
>>> range(100)[5:18:2]
[5, 7, 9, 11, 13, 15, 17]
The third parameter is the step. So [::3] would return every 3rd element of the list/string.
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".
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]