This tutorial will discuss about unique ways to access first element from list of tuples in Python.
Table Of Contents
Method 1: Using List Comprehension
Iterate our all the tuples in the list using a List Comprehension, and select first
element of each tuple during iteration. The List Comprehension will build a new list containing only the first elements of each tuple from the list.
Let’s see the complete example,
listOfTuples = [(33, 44, 55, 66, 77), (78, 98, 71, 20, 33), (48, 10, 34, 27, 58), (17, 27, 37, 47, 57)] # Loop over list of tuples, and select first # element from each tuple using List comprehension elements = [tupleObj[0] for tupleObj in listOfTuples] print (elements)
Output
[33, 78, 48, 17]
Method 2: Using map() and itemgetter()
To get every first element from a list of tuples, use the map() function, to apply the operator.itemgetter(0)
method on every tuple in the list. For each tuple, the itemgetter(0)
function will select its first element. The map()
function will return a mapped object containing every first element of every tuple in the list. Then we can pass this mapped object to the list()
function, to create a list containing the first
element of each tuple from the main list.
Let’s see the complete example,
Frequently Asked:
import operator listOfTuples = [(33, 44, 55, 66, 77), (78, 98, 71, 20, 33), (48, 10, 34, 27, 58), (17, 27, 37, 47, 57)] # Apply itemgetter() function on each tuple in list to # select first element from each tuple, and add them to a list elements = list(map(operator.itemgetter(0), listOfTuples)) print (elements)
Output
[33, 78, 48, 17]
Summary
We learned about different ways to access every first element from a list of tuples in Python. Thanks.