This tutorial will discuss about unique ways to get every nth element in a list in Python.
Table Of Contents
Method 1: Using Slicing
We can slice some elements from a list using the slicing operator i.e.
list[start, end , N]
It will select every Nth
element from list from start
to end
index positions in list. Default value of start
is 0, and the default value of end
is the end of list. So, to get a sublist containing every Nth
element from list, use the default values of start, and end. Also, provide the step size N in slicing operator i.e.
# Select every Nth element from List subList = listOfNumbers[ : : N]
It should return a sublist containing every Nth
element from list.
Let’s see the complete example,
listOfNumbers = [12, 42, 44, 68, 91, 72, 71, 81, 82, 91, 92, 93] N = 3 # Select every Nth element from List subList = listOfNumbers[ : : N] print(subList)
Output
Frequently Asked:
[12, 68, 71, 91]
Method 2: Using itertools.islice()
The itertools provides a method islice()
. It accepts the following arguments,
- An iterable sequence, from which we need to slice the elements.
- The start position in the sequence, from which it will start the slicing. Default value is
0
. - The end position in the sequence, at which it will stop the slicing. Default value is
None
i.e. end of list. - Step size N: It specifies the number of values that need to be skipped between successive calls.
It selects every Nth element in the range, and returns an iterator pointing to the selected elements. We can use it to select every Nth element from a complete list.
Let’s see the complete example,
import itertools listOfNumbers = [12, 42, 44, 68, 91, 72, 71, 81, 82, 91, 92, 93] N= 3 # Select every Nth element from List subList = list(itertools.islice(listOfNumbers, 0, None, N)) print (subList)
Output
[12, 68, 71, 91]
Summary
We learned about different ways to get every Nth element from a List in Python. Thanks.