Get the last element of a tuple in Python

avatar

Borislav Hadzhiev

Last updated: Jun 30, 2022

banner

Check out my new book

Get the last 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]. When an index starts with a minus, we start counting backwards from the end of the tuple.

main.py
my_tuple = ('a', 'b', 'c', 'd') last = my_tuple[-1] print(last) # 👉️ 'd' first = my_tuple[0] print(first) # 👉️ 'a'

We used an index of -1 to get the last item of a tuple.

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

If you need to get the second to last element of a tuple, use an index of -2.

main.py
my_tuple = ('a', 'b', 'c', 'd') print(my_tuple[-2]) # 👉️ 'c'

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

Since indexes are zero based, you can also get the index of the last item in the tuple by subtracting 1 from the tuple's length.

main.py
my_tuple = ('a', 'b', 'c', 'd') last = my_tuple[len(my_tuple) - 1] print(last) # 👉️ 'd'

The len() function returns the length (the number of items) of an object.

main.py
my_tuple = ('a', 'b', 'c', 'd') print(len(my_tuple)) # 👉️ 4
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

You won't see this approach being used in Python because it's much easier and more direct to use and index of -1.

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

main.py
my_tuple = () # ⛔️ IndexError: tuple index out of range last = my_tuple[-1]

If you need to handle a scenario where your tuple is empty, use a try/except block.

main.py
my_tuple = () try: last = my_tuple[-1] except IndexError: # 👇️ this runs print('tuple is empty')

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 = () try: last = 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.

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.