Categories
Python Answers

How to extract the n-th elements from a list of tuples with Python?

Spread the love

Sometimes, we want to extract the n-th elements from a list of tuples with Python.

In this article, we’ll look at how to extract the n-th elements from a list of tuples with Python.

How to extract the n-th elements from a list of tuples with Python?

To extract the n-th elements from a list of tuples with Python, we can use list comprehension.

For instance, we write:

elements = [(1, 1, 1), (2, 3, 7), (3, 5, 10)]
n = 1
e = [x[n] for x in elements]
print(e)

We get the n-th element from each tuple and put them into a list with [x[n] for x in elements].

x is the tuple being retrieved.

Therefore, e is [1, 3, 5].

Conclusion

To extract the n-th elements from a list of tuples with Python, we can use list comprehension.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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