Get the second element of a tuple in Python

avatar

Borislav Hadzhiev

Last updated: Jul 2, 2022

banner

Check out my new book

Get the second element of a tuple in Python #

Access the tuple element at index 1 to get the last element of a tuple, 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 second element of a tuple my_tuple = ('one', 'two', 'three') second_item = my_tuple[1] print(second_item) # 👉️ two # --------------------------------------------- # ✅ get 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']

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.

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.

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

main.py
my_tuple = ('one',) # ⛔️ IndexError: tuple index out of range 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 = ('one',) try: second_item = my_tuple[1] except IndexError: # 👇️ this runs print('Tuple does not have a second element')

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 = ('one',) 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.

If you need to get the second element from a list of tuples, use a list comprehension.

main.py
list_of_tuples = [('a', 'b'), ('c', 'd'), ('e', 'f')] result = [tup[1] for tup in list_of_tuples] print(result) # 👉️ ['b', 'd', 'f']

We used a list comprehension to get a new list that contains the second 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.

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.