Get the Nth element of a Tuple or List of Tuples in Python

avatar
Borislav Hadzhiev

Last updated: Feb 19, 2023
5 min

banner

# Table of Contents

  1. Get the Nth element of a Tuple in Python
  2. Get the Nth element from a list of tuples in Python
  3. Get the Nth element from a list of tuples using a for loop
  4. Get the Nth element from a list of tuples using map()
  5. Get the Nth element from a list of tuples using zip()
  6. Get the Nth element from a list of tuples using a dictionary

# Get the Nth element of a Tuple in Python

Access the tuple at index N - 1 to get the Nth element, e.g. my_tuple[1].

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

main.py
# โœ… get the second element of a tuple my_tuple = ('bobby', 'hadz', 'com') second_item = my_tuple[1] print(second_item) # ๐Ÿ‘‰๏ธ hadz # --------------------------------------------- # โœ… get the second element from a list of tuples list_of_tuples = [('a', 'b'), ('c', 'd'), ('e', 'f')] result = [tup[1] for tup in list_of_tuples] print(result) # ๐Ÿ‘‰๏ธ ['b', 'd', 'f']

get nth element of tuple

We used an index of 1 to get the second element of a tuple.

Python indexes are zero-based, so the first element in a tuple has an index of 0, the second an index of 1, etc.
main.py
my_tuple = ('bobby', 'hadz', 'com') first_item = my_tuple[0] print(first_item) # ๐Ÿ‘‰๏ธ bobby last_item = my_tuple[-1] print(last_item) # ๐Ÿ‘‰๏ธ com

When the index starts with a minus, we start counting backward from the end of the tuple.

For example, the index -1 gives us access to the last element, -2 to the second-last, etc.

If you try to access a tuple at an index that is out of bounds, you'd get an IndexError.

main.py
my_tuple = ('bobby',) # โ›”๏ธ IndexError second_item = my_tuple[1]

If you need to handle a scenario where your tuple is empty or only contains 1 element, use a try/except block.

main.py
my_tuple = ('bobby',) try: second_item = my_tuple[1] except IndexError: # ๐Ÿ‘‡๏ธ this runs print('The tuple does not have a second element')

using try except to handle potential index error

We try to access the tuple at index 1, and if an IndexError is raised, we handle it in the except block.

You can use the pass statement if you want to ignore the error.

main.py
my_tuple = ('bobby',) try: second_item = my_tuple[1] except IndexError: # ๐Ÿ‘‡๏ธ this runs pass

The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

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

If you need to get the Nth element of each tuple in a list, use a list comprehension.

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) # ๐Ÿ‘‰๏ธ ['!', '@', '#']

get nth element from list of tuples

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 backward 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.

# Get the Nth element from a list of tuples using a for loop

This is a three-step process:

  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]

get nth element from list of tuples using for loop

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.

# Get the Nth element from a list of tuples using map()

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]

get nth element from list of tuples using map

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

The operator.itemgetter class 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.

You can also use a lambda function instead of the itemgetter class.

main.py
list_of_tuples = [('a', 1, '!'), ('b', 2, '@'), ('c', 3, '#')] second = list(map(lambda x: x[1], list_of_tuples)) print(second) # ๐Ÿ‘‰๏ธ [1, 2, 3]

The lambda function gets called with each tuple in the list and returns the first element.

# Get the Nth element from a list of tuples using zip()

You can also use the zip() function to get the Nth element from a list of tuples.

main.py
list_of_tuples = [('bobby', 1), ('hadz', 2), ('com', 3)] last = list(zip(*list_of_tuples))[0] print(last) # ๐Ÿ‘‰๏ธ ('bobby', 'hadz', 'com') last = list(zip(*list_of_tuples))[-1] print(last) # ๐Ÿ‘‰๏ธ (1, 2, 3)

get nth element from list of tuples using zip

The zip function iterates over several iterables in parallel and produces tuples with an item from each iterable.

The zip function returns an iterator of tuples.

main.py
list_1 = [1, 2, 3] list_2 = ['bobby', 'hadz', 'com'] my_zip = list(zip(list_1, list_2)) # ๐Ÿ‘‡๏ธ [(1, 'bobby'), (2, 'hadz'), (3, 'com')] print(my_zip)

We used the iterable unpacking * operator to unpack the list of tuples in the call to zip().

main.py
list_of_tuples = [('bobby', 1), ('hadz', 2), ('com', 3)] # [('bobby', 'hadz', 'com'), (1, 2, 3)] print(list(zip(*list_of_tuples)))

The last step is to access the list of tuples at a specific index.

# Get the Nth element from a list of tuples using a dictionary

If each tuple in your list has 2 elements, you can also use the dict.keys() and dict.values() methods to get the Nth element from a list of tuples.

main.py
list_of_tuples = [('bobby', 1), ('hadz', 2), ('com', 3)] a_list = list(dict(list_of_tuples).values()) print(a_list) # ๐Ÿ‘‰๏ธ [1, 2, 3] a_list = list(dict(list_of_tuples).keys()) print(a_list) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz', 'com']

get nth element from list of tuples using dictionary

We used the dict() class to convert the list to a dictionary.

The dict.values method returns a new view of the dictionary's values.

main.py
my_dict = {'id': 1, 'name': 'bobbyhadz'} print(my_dict.values()) # ๐Ÿ‘‰๏ธ dict_values([1, 'bobbyhadz'])

The dict.keys method returns a new view of the dictionary's keys.

main.py
my_dict = {'id': 1, 'name': 'BobbyHadz'} print(my_dict.keys()) # ๐Ÿ‘‰๏ธ dict_keys(['id', 'name'])

The last step is to convert the view object to a list by using the list() class.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev