This tutorial will discuss about unique ways to get every nth element from a list of tuples in Python.
Table Of Contents
Method 1: Using map() and itemgetter()
Using the map() function, apply the function operator.itemgetter(n)
on every tuple in the list. For each tuple, the itemgetter(n)
function will select the nth element of the tuple. The map()
function will return a mapped object containing every nth element of every tuple in the list. Then we can pass this mapped object to the list()
function, to create a list containing the nth
element of each tuple from the main list.
Let’s see the complete example,
import operator listOfTuples = [(11, 12, 13, 14, 15), (18, 28, 38, 48, 58), (11, 22, 33, 44, 55), (17, 27, 37, 47, 57)] n = 2 # Apply itemgetter() function on each tuple in list to # select nth element from each tuple, and add them to a list elements = list(map(operator.itemgetter(n), listOfTuples)) print (elements)
Output
[13, 38, 33, 37]
Method 2: Using List Comprehension
Iterate our all the tuples in the list using a List Comprehension, and select nth
element of each tuple during iteration. The List Comprehension will build a new list containing only the nth element of each tuple from the list.
Let’s see the complete example,
Frequently Asked:
listOfTuples = [(11, 12, 13, 14, 15), (18, 28, 38, 48, 58), (11, 22, 33, 44, 55), (17, 27, 37, 47, 57)] n = 2 # Loop over list of tuples, and select nth # element from each tuple using List comprehension elements = [tupleObj[n] for tupleObj in listOfTuples] print (elements)
Output
[13, 38, 33, 37]
Method 3: Using zip() function
Decouple all the tuples in the list as individual arguments and pass them to the zip()
function. It will return a zipped object. Then convert the zipped object to list.
This list have multiple sublist, where each ith
sublist will contain the ith
element from each tuple of the original list. As we were interested in only the nth
element of each tuple from the original list, so select the nth
sublist from this new list.
Let’s see the complete example,
listOfTuples = [(11, 12, 13, 14, 15), (18, 28, 38, 48, 58), (11, 22, 33, 44, 55), (17, 27, 37, 47, 57)] n = 2 # Decouple all the tuples in list, and zip them together, # select nth entry from zipped object elements = list(zip(*listOfTuples))[n] print (elements)
Output
(13, 38, 33, 37)
Summary
We learned about different ways to get every Nth element from a list of tuples in Python. Thanks.