p.brown p.brown - 4 months ago 21
Python Question

Pythonic way to return list of every n'th item in a larger list

Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]

Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line?

Answer
>>> l = range(165)
>>> l[0::10]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]

EDIT: just for fun, a little timing comparison (ignoring the boundary condition):

$ python -m timeit -s "l = range(1000)" "l1 = [x for x in l if x % 10 == 0]"
1000 loops, best of 3: 525 usec per loop
$ python -m timeit -s "l = range(1000)" "l1 = l[0::10]"
100000 loops, best of 3: 4.02 usec per loop