Pythonic way to return list of every nth item in a larger list


Question

Say we have a list of numbers from 0 to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item, i.e. [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?

1
144
5/24/2017 4:19:53 PM

Accepted 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
243
9/10/2009 7:18:29 AM

  1. source_list[::10] is the most obvious, but this doesn't work for any iterable and is not memory efficient for large lists.
  2. itertools.islice(source_sequence, 0, None, 10) works for any iterable and is memery efficient, but probably is not the fastest solution for large list and big step.
  3. (source_list[i] for i in xrange(0, len(source_list), 10))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon