We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

Get First Column from List of Tuples in Python

This tutorial will discuss about unique ways to get first column from list of tuples in Python.

Table Of Contents

Method 1: Using map() and itemgetter()

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, and first element of each tuple will give us first column from List of Tuples.

Advertisements

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 column from list of tuples.

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)]

# Get first column from list of tuples
column = list(map(operator.itemgetter(0), listOfTuples))

print (column)

Output

[33, 78, 48, 17]

Method 2: Using List Comprehension

Iterate our all the tuples in the list using a List Comprehension, and select first element of each tuple. The List Comprehension will build a new list containing only the first elements of each tuple from the list i.e. the first column from list of tuples.

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)]

# Get first column from list of tuples
column = [tupleObj[0] for tupleObj in listOfTuples]

print (column)

Output

[33, 78, 48, 17]

Summary

We learned about different ways to get the first column from a List of tuples in Python. Thanks.

15
541.215,95