Get first element of each tuple in a list in python

Python – Get First Element of Each Tuple in List

In this tutorial, we will look at how to get the first element of each tuple from a list of tuples in Python with the help of some examples.

Get first element of each tuple in a list in python

Let’s look at some methods with the help of examples.

The straightforward way is to loop over each tuple in the list and append its first element to our result list or tuple.

# list of tuples
employees = [("Jim", "Scranton"), ("Ryan", "New York"), ("Dwight", "Scranton")]
# get first element of each tuple
names = []
for e in employees:
    names.append(e[0])
# display the result
print(names)

Output:

['Jim', 'Ryan', 'Dwight']

We get a list of the first items in each tuple. The resulting list names contains the names from each tuple in the list employees.

You can also use list comprehension to reduce the above code (to get the first element of each tuple in Python) to a single line.

# list of tuples
employees = [("Jim", "Scranton"), ("Ryan", "New York"), ("Dwight", "Scranton")]
# get first element of each tuple
names = [e[0] for e in employees]
# display the result
print(names)

Output:

['Jim', 'Ryan', 'Dwight']

We get the same result as above.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

You can similarly use the above methods to get the last element in each tuple. Use the -1 index to access the last element from a tuple. Let’s use the list comprehension method to get a list of all the last elements from each tuple in the original list.

# list of tuples
employees = [("Jim", "Scranton"), ("Ryan", "New York"), ("Dwight", "Scranton")]
# get last element of each tuple
city = [e[-1] for e in employees]
# display the result
print(city)

Output:

['Scranton', 'New York', 'Scranton']

You can see that the new list has only the last elements from the tuples in the original list. The resulting list city contains the name of the city for each employee in the list employee.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top