Get the Nth element from a list of tuples in Python

avatar

Borislav Hadzhiev

Last updated: Jul 2, 2022

banner

Check out my new book

Get the Nth element from a list of tuples in Python #

Use a list comprehension to get the Nth element of each tuple in a list, e.g. result = [tup[N] for tup in list_of_tuples]. The list comprehension iterates over the list and returns the Nth element from each tuple.

main.py
list_of_tuples = [('a', 1, '!'), ('b', 2, '@'), ('c', 3, '#')] first = [tup[0] for tup in list_of_tuples] print(first) # 👉️ ['a', 'b', 'c'] second = [tup[1] for tup in list_of_tuples] print(second) # 👉️ [1, 2, 3] last = [tup[-1] for tup in list_of_tuples] print(last) # 👉️ ['!', '@', '#']

We used a list comprehension to get a new list that contains the Nth element of each tuple.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we access the tuple element at the specific index and return the result.

Python indexes are zero-based, so the first element in a tuple has an index of 0, the second an index of 1, etc.

When the index starts with a minus, we start counting backwards from the end of the tuple. For example, the index -1 gives us access to the last element, -2 to the second-last, etc.

Alternatively, you can use a for loop.

To get the Nth element of each tuple in a list:

  1. Declare a new variable and set it to an empty list.
  2. Use a for loop to iterate over the list of tuples.
  3. On each iteration, append the Nth tuple element to the new list.
main.py
list_of_tuples = [('a', 1, '!'), ('b', 2, '@'), ('c', 3, '#')] second = [] for tup in list_of_tuples: second.append(tup[1]) print(second) # 👉️ [1, 2, 3]

We simply iterate over the list of tuples and append the Nth item of each tuple to a new list.

The list.append() method adds an item to the end of the list.

Alternatively, you can use the map() function.

main.py
from operator import itemgetter list_of_tuples = [('a', 1, '!'), ('b', 2, '@'), ('c', 3, '#')] second = list(map(itemgetter(1), list_of_tuples)) print(second) # 👉️ [1, 2, 3]

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The operator.itemgetter method returns a callable object that fetches the item at the specified index.

For example, x = itemgetter(1) and then calling x(my_tuple), returns my_tuple[1].

On each iteration, we get the Nth element of the tuple and return it.

The map() function returns a map object, so we had to use the list() class to convert the result to a list.

Which approach you pick is a matter of personal preference. I'd go with the list comprehension as I find it more direct and easier to read.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.