Search for every nth item in a list

I try to find every nth item in the list, but I pretty much lost it. Here is my code:

def returnNth(lst, n):
'list ==> list, return every nth element in lst for n > 0'
res = []
for a in lst:
    res = res + [a[::n]]
return res

I realized that [[[n]] can be used to search for the result, but I just get the error message that int is not decryptable. For list [1,2,3,4,5,6], returnNth (l, 2) should return [1,3,5] and for list ["dog", "cat", 3, "hamster", True] , returnNth (u, 2) should return ['dog', 3, True] What can I fix this?

+5
source share
3 answers

You only need lst[::n], there is no need to iterate over the list items at all.

Example:

>>> lst=[1,2,3,4,5,6,7,8,9,10]
>>> lst[::3]
[1, 4, 7, 10]
>>> 
+24
source

you can use list comprehension here, for example:

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]
+2
source

n- ....

  def returnNth(lst, n):
        # 'list ==> list, return every nth element in lst for n > 0'
        return lst[::n]
+1

All Articles