Today I Learned

A Hashrocket project

Steppin' and Slicin' through lists

Python allows you to slice a list with a range, which is common. But what is less common is adding a step variable to the same syntax construct.

A range takes on the form of start:end in python, but it allows you to default to the start and end of the data with just :.

[0, 1, 2, 3, 4, 5, 6][:]
# [0, 1, 2, 3, 4, 5, 6]

Add some numbers in there and it looks like this:

[0, 1, 2, 3, 4, 5, 6][2:5]
# [2, 3, 4]

But bolted on syntax allows you to step as well.

[0, 1, 2, 3, 4, 5, 6][2:5:2]
# [2, 4]

The form is actually start:end:step. Leaving out the start and end looks weird but allows you to get all even indexed elements:

[0, 1, 2, 3, 4, 5, 6][::2]
# [0, 2, 4, 6]