Get every second element from a List of tuples in Python

This tutorial will discuss about unique ways to get every second element from a 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 second element of each tuple during iteration. The List Comprehension will build a new list containing only the second 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 second
# element from each tuple using List comprehension
elements = [tupleObj[1] for tupleObj in listOfTuples]

print (elements)

Output

[44, 98, 10, 27]

Method 2: Using map() and itemgetter()

To get every second element from a list of tuples, use the map() function, to apply the operator.itemgetter(1) method on every tuple in the list. For each tuple, the itemgetter(1) function will select its second element. The map() function will return a mapped object containing every second element of every tuple in the list. Then we can pass this mapped object to the list() function, to create a list containing the second element of each tuple from the main list.

Let’s see the complete example,

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 second element from each tuple, and add them to a list
elements = list(map(operator.itemgetter(1), listOfTuples))

print (elements)

Output

[44, 98, 10, 27]

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 second element of each tuple from the original list, so select the sublist at index 1 from this new 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)]

# Decouple all the tuples in list, and zip them together,
# select second entry from zipped object
elements = list(zip(*listOfTuples))[1]

print (elements)

Output

(44, 98, 10, 27)

Summary

We learned about different ways to get every second element from a list of tuples in Python. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top