Open In App

Get first element from a List of tuples - Python

Last Updated : 22 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The goal here is to extract the first element from each tuple in a list of tuples. For example, given a list [(1, 'sravan'), (2, 'ojaswi'), (3, 'bobby')], we want to retrieve [1, 2, 3], which represents the first element of each tuple. There are several ways to achieve this, each varying in terms of efficiency and readability. Let's explore different approaches to accomplish this task.

Using list comprehension

List comprehension is considered one of the most efficient way to iterate over a collection and transform elements, all in a single line.

Python
a = [(1, 'sravan'), (2, 'ojaswi'),(3, 'bobby'), (4, 'rohith'),(5, 'gnanesh')]

res = [x[0] for x in a]
print(res)

Output
[1, 2, 3, 4, 5]

Explanation: [x[0] for x in a] iterates over each tuple in the list "a", extracts the first element x[0] from each tuple and creates a new list res containing these first elements.

Using for loop

For loop is efficient and easy to understand but may have slightly more overhead due to the explicit iteration and function calls.

Python
a = [(1, 'sravan'), (2, 'ojaswi'),(3, 'bobby'), (4, 'rohith'),(5, 'gnanesh')]

for x in a:
    print(x[0])

Output
1
2
3
4
5

Explanation: For loop iterates through each tuple in the list a, accesses the first element (x[0]) and prints it.

Using map()

map() applies a function to all elements in the list. This is a bit more functional, but less intuitive than a loop or comprehension.

Python
a = [(1, 'sravan'), (2, 'ojaswi'),(3, 'bobby'), (4, 'rohith'),(5, 'gnanesh')]

res = list(map(lambda x: x[0], a))
print(res)

Output
[1, 2, 3, 4, 5]

Explanation: map() function applies lambda x: x[0] to each tuple in a, extracting the first element. The iterator returned by map() is then converted to a list using list() and stored in res.

Using generator expression

A generator expression is like a list comprehension but without creating an entire list in memory, which can be useful for large datasets.

Python
a = [(1, 'sravan'), (2, 'ojaswi'),(3, 'bobby'), (4, 'rohith'),(5, 'gnanesh')]

res = (x[0] for x in a)
for i in res:
    print(i)

Output
1
2
3
4
5

Explanation: (x[0] for x in a) creates an iterator that yields the first element of each tuple in a, generating values one at a time without storing the entire list in memory.

Similar Reads:


Next Article
Practice Tags :

Similar Reads