8

How can I find every nth element of a list?

For a list [1,2,3,4,5,6], returnNth(l,2) should return [1,3,5] and for a list ["dog", "cat", 3, "hamster", True], returnNth(u,2) should return ['dog', 3, True]. How can I do this?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
iKyriaki
  • 589
  • 4
  • 14
  • 26
  • 1
    its was introduced in python2.3; see the docs for that--> http://docs.python.org/release/2.3.5/whatsnew/section-slices.html – namit Feb 04 '13 at 04:19

3 Answers3

47

You just need lst[::n].

Example:

>>> lst=[1,2,3,4,5,6,7,8,9,10]
>>> lst[::3]
[1, 4, 7, 10]
>>> 
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
us2012
  • 16,083
  • 3
  • 46
  • 62
3
In [119]: def returnNth(lst, n):
   .....:     return lst[::n]
   .....:

In [120]: returnNth([1,2,3,4,5], 2)
Out[120]: [1, 3, 5]

In [121]: returnNth(["dog", "cat", 3, "hamster", True], 2)
Out[121]: ['dog', 3, True]
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
avasal
  • 14,350
  • 4
  • 31
  • 47
-1

I you need the every nth element....

  def returnNth(lst, n):
        # 'list ==> list, return every nth element in lst for n > 0'
        return lst[::n]
sufinsha
  • 755
  • 6
  • 9
  • 1
    -1; this doesn't add anything new that wasn't already provided by the other two answers, posted 10 minutes' earlier. – Mark Amery Nov 16 '19 at 15:09