Return multiple values and only use One in Python

avatar

Borislav Hadzhiev

Last updated: Aug 17, 2022

banner

Photo from Unsplash

Return multiple values and only use One in Python #

To return multiple values from a function and only use one:

  1. Use parentheses to call the function.
  2. Use square brackets to access the value at the specific index.
main.py
def my_func(): return 'one', 'two', 'three' # ✅ Return multiple values from function and only use one first = my_func()[0] print(first) # 👉️ 'one second = my_func()[1] print(second) # 👉️ 'two' third = my_func()[2] print(third) # 👉️ 'three' # ---------------------------- _, second, _ = my_func() print(second) # 👉️ 'two' # ---------------------------- first, *_ = my_func() print(first) # 👉️ 'one'

Make sure to use parentheses to call the function before accessing a value at a specific index.

main.py
def my_func(): return 'one', 'two', 'three' first = my_func()[0] print(first) # 👉️ 'one
Python indexes are zero-based, so the first element in a collection (e.g. a list or a tuple) has an index of 0, and the last element has an index of -1 or len(collection) - 1.

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

You can use a try/except statement if you need to handle the error.

main.py
def my_func(): return 'one', 'two', 'three' try: first = my_func()[100] print(first) # 👉️ 'one except IndexError: pass

The specified index is out of range, so the except block runs.

Alternatively, you can use unpacking to only use one of multiple returned values from a function.

main.py
def my_func(): return 'one', 'two', 'three' _, second, _ = my_func() print(second) # 👉️ 'two'
When unpacking, make sure to declare exactly as many variables as there are items in the iterable.

When unpacking from a tuple or list, each variable declaration counts for a single item.

Make sure to declare exactly as many variables as there are items in the tuple or list.

You can use underscores for the values you are not interested in.

If you try to unpack more or less values than there are in the collection, you would get an error.

You can also use the iterable unpacking operator to store the rest of the items after you have assigned the one value you need to a variable.

main.py
def my_func(): return 'one', 'two', 'three' first, *_ = my_func() print(first) # 👉️ 'one' print(_) # 👉️ ['two', 'three']

The * iterable unpacking operator enables us to unpack an iterable in function calls, in comprehensions, in generator expressions and when assigning to a variable.

The underscore _ variable stores all of the values the function returns after the first value.

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.