4el3ta
Last Updated: February 25, 2016
·
1.675K
· lyndsysimon
42595607ede5ee9c75f4da244128a082

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
Say Thanks
Respond

3 Responses
Add your response

6985
660bb878ae25be5b78c87508f64e68f5

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

over 1 year ago ·
6986
42595607ede5ee9c75f4da244128a082

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 ·
6991
42595607ede5ee9c75f4da244128a082

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 ·