views:

440

answers:

6

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.

+5  A: 

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'
Justin Ethier
+18  A: 

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.

deinst
Sequence addresses, not array addresses. Besides, they're called lists in Python.
Adriano Varoli Piazza
@Adriano Yes, I'll fix it
deinst
+15  A: 

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

Adriano Varoli Piazza
wow didn't know that!!
iamgopal
+8  A: 

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]
Yuval A
Incorrect by being too specific in that it can be any kind of sequence, not just a list.
Adriano Varoli Piazza
edited, thanks Adriano.
Yuval A
+4  A: 

The third parameter is the step. So [::3] would return every 3rd element of the list/string.

lupefiasco
Array? is that a fancy php term for a list? :)
Adriano Varoli Piazza
^ Good call, fixed ;)
lupefiasco
+4  A: 

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]
Bolo