Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

People also ask

How do you select every nth item in a list Python?

To get every nth element in a list, a solution is to do mylist[::n].

How do you print every nth element from an array?

To get every Nth element of an array:Declare an empty array variable. Use a for loop to iterate the array every N elements. On each iteration, push the element to the new array. The final array will contain every Nth element of the original array.

How do I get every other element in a list?

Another way to get every other element from a list is by using the Python enumerate function. What can we do with this object? You can use an enumerate object to print index and value for each element in a list.


>>> lst = list(range(165))
>>> lst[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 "lst = list(range(1000))" "lst1 = [x for x in lst if x % 10 == 0]"
1000 loops, best of 3: 525 usec per loop
$ python -m timeit -s "lst = list(range(1000))" "lst1 = lst[0::10]"
100000 loops, best of 3: 4.02 usec per loop

  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 memory-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))

You can use the slice operator like this:

l = [1,2,3,4,5]
l2 = l[::2] # get subsequent 2nd item

Use range(start, end, step)

li = list(range(0, 1000, 10))

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90 ... 990]

Or, if you have a list use slice: From manual: s[i:j:k] slice of s from i to j with step k

yourlist = [0, ... ,10 ...]  
sub = yourlist[::10]  # same as yourlist[0:100:10]

>>> sub
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

newlist = oldlist[::10]

This picks out every 10th element of the list.