Last Updated: February 25, 2016
·
1.88K
· lyndsysimon

Python's slice notation's obscure secret

Okay, so maybe it isn't that obscure - but it isn't often used that's I've seen.

There is a third parameter in the slice syntax, called the stride. It is the number of characters to advance for each "unit" in the slice. The default is 1.

The following are equivalent:

foo = [0,1,2,3,4,5,6,7,8]
foo[:]
> [0,1,2,3,4,5,6,7,8]
foo[::1]
> [0,1,2,3,4,5,6,7,8]

What if you wanted only the even indexes? You could write an iterator or a loop, but you can also do it this way:

foo[::2]
> [0,2,4,6,8]

Cool! Reversing a string is just as easy:

bar = 'asdf'
bar
> asdf
bar[::-1]
> fdsa

3 Responses
Add your response

foo[::2] is even indices though, not odd ones :) odd would be foo[1::2]

over 1 year ago ·

Good catch :) I said "indexes", but I was thinking "values".

You never completely grow out of off-by-one errors, it seems...

over 1 year ago ·

I've updated the example to fix your catch. I also ended up changing the values of my example list, since saying we're getting even keys and showing odd vlaues messes with my head.

over 1 year ago ·