Make a new list containing every Nth item in the original list

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

Note that this is around 100 times faster than looping and checking a modulus for each element:

$ python -m timeit -s "xs = list(range(1000))" "[x for i, x in enumerate(xs) if i % 10 == 0]"
500 loops, best of 5: 476 usec per loop

$ python -m timeit -s "xs = list(range(1000))" "xs[0::10]"
100000 loops, best of 5: 3.32 usec per loop

Leave a Comment