Search code examples
listpython

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


Say we have a list of integers from 0 to 1000:

[0, 1, 2, 3, ..., 997, 998, 999]

How do I get a new list containing the first and every subsequent 10th item?

[0, 10, 20, 30, ..., 990]

I can do this using a for loop, but is there a neater way, perhaps even in one line of code?


Solution

  • >>> 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