Get Every Nth Element From ListDevelop a method that returns every Nth element from a list in a new list.
This page was last reviewed on Jun 28, 2023.
Nth element. Suppose you have a list with several elements, and you want to take every other element from the list. This logic filters on the index, and returns the required elements.
Python code that uses lambda expressions and methods like filter() or map() can be effective. But often it is clearer to just use a for-loop.
Required output. Consider a list with 4 values: the one-character strings from "abcd." By taking every second element (argument 2) we should get "a" and "c."
Input: a, b, c, d Nth 2: a, c
Example code. To begin, we introduce a method called every_nth_element. This receives a list, and the "Nth" value "n." So if we pass 2, we get every second element.
Info The method loops over each element in the list with enumerate(), which returns both indexes and values.
And If the index of the element is evenly divisible by the "n" argument, we add it to the list. The list is returned at the end.
def every_nth_element(items, n): results = [] # Loop over elements and indexes. for i, value in enumerate(items): # If evenly divisible, accept the element. if i % n == 0: results.append(value) return results # Input values. values = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] # Get every other element. x1 = every_nth_element(values, 2) print(x1) # Get every third element. x2 = every_nth_element(values, 3) print(x2)
['a', 'c', 'e', 'g', 'i'] ['a', 'd', 'g']
A review. This code is the same logic as the Nth-child selector from CSS. We get alternating elements with Nth-child. The "every_nth_element" def here has the same utility.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 28, 2023 (edit).
© 2007-2023 Sam Allen.