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.
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
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.
enumerate()
, which returns both indexes and values.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']
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.