Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding every nth element in a list

Tags:

python

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?

like image 955
iKyriaki Avatar asked Feb 04 '13 04:02

iKyriaki


2 Answers

You just need lst[::n].

Example:

>>> lst=[1,2,3,4,5,6,7,8,9,10]
>>> lst[::3]
[1, 4, 7, 10]
>>> 
like image 76
us2012 Avatar answered Sep 22 '22 07:09

us2012


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]
like image 33
avasal Avatar answered Sep 22 '22 07:09

avasal