Python – Get first element in List of tuples
In this article. we will discuss how to get the first element in the list of tuples in Python.
Create a list of tuples and display them:
Python3
# create tuples with college# id and name and store in a listdata=[(1,'sravan'), (2,'ojaswi'), (3,'bobby'), (4,'rohith'), (5,'gnanesh')] # display dataprint(data) |
Output:
[(1, ‘sravan’), (2, ‘ojaswi’), (3, ‘bobby’), (4, ‘rohith’), (5, ‘gnanesh’)]
Method 1: Using iteration (for loop)
We can iterate through the entire list of tuples and get first by using the index, index-0 will give the first element in each tuple in a list.
Syntax: for var in list_of_tuple:
print(var[0])
Example: Here we will get the first IE student id from the list of tuples.
Python3
# create tuples with college id# and name and store in a listdata = [(1,'sravan'), (2,'ojaswi'), (3,'bobby'),(4,'rohith'), (5,'gnanesh')] # iterate using for loop# to access first elementsfor i in data: print(i[0]) |
Output:
1 2 3 4 5
Method 2: Using zip function
Zip is used to combine two or more data/data structures. Here we can use zip() function by using the index as 0 to get the first element.
Syntax: list(zip(*data))[0]
Example: Python code to access first element in List of the tuple.
Python3
# create tuples with college id# and name and store in a listdata = [(1,'sravan'),(2,'ojaswi'), (3,'bobby'),(4,'rohith'), (5,'gnanesh')] # get first element using zipprint(list(zip(*data))[0]) |
Output:
(1, 2, 3, 4, 5)
Method 3: Using map with itemgetter() method
Here we are using the map function along with itemgetter() method to get the first elements, here also we are using index – 0 to get the first elements. itemgetter() method is available in the operator module, so we need to import operator
Syntax: map(operator.itemgetter(0), data)
Example: Python program to access first elements.
Python3
import operator # create tuples with college id# and name and store in a listdata = [(1,'sravan'),(2,'ojaswi'), (3,'bobby'),(4,'rohith'), (5,'gnanesh')] # map the data using item# getter method with first elementsfirst_data = map(operator.itemgetter(0), data) # display first elementsfor i in first_data: print(i) |
Output:
1 2 3 4 5
Method 4: Using map() with lambda expression
Here we are using lambda expression along with map() function, here also we are using index 0 to get the first data.
Syntax: map(lambda x: x[0], data)
Where,
- x is an iterator to get first elements
- data is the list of tuples data
Example: Python code to access first elements.
Python3
# create tuples with college id# and name and store in a listdata=[(1,'sravan'),(2,'ojaswi'), (3,'bobby'),(4,'rohith'), (5,'gnanesh')] # map with lambda expression to get first elementfirst_data = map(lambda x: x[0], data) # display datafor i in first_data: print(i) |
Output:
1 2 3 4 5






Please Login to comment...