Borislav Hadzhiev
Last updated: Jun 29, 2022
Check out my new book
Access the element at its specific index to get an element from a tuple, e.g.
first = my_tuple[0]
. Indexes are zero based, so the first item in the tuple
has an index of 0
, the second an index of 1
, and the last an index of
-1
.
my_tuple = ('a', 'b', 'c') first = my_tuple[0] print(first) # 👉️ 'a' second = my_tuple[1] print(second) # 👉️ 'b' last = my_tuple[-1] print(last) # 👉️ 'c' # ----------------- # 👇️ access element from a tuple returned from a function def example_func(): return ('a', 'b', 'c') first = example_func()[0] print(first) # 👉️ 'a'
We can use square brackets to get an element from a tuple.
The first item in a tuple has an index of 0
, and the last an index of -1
.
If you need to get the Nth element of a tuple, specify the element's index, e.g.
to get the second item in the tuple use an index of 1
.
my_tuple = ('a', 'b', 'c') first = my_tuple[0] print(first) # 👉️ 'a' second = my_tuple[1] print(second) # 👉️ 'b'
The same approach can be used to get an element from a list.
If you are trying to get an element from a tuple that is returned from a function, make sure to invoke the function using parenthesis before using square brackets to access the tuple at an index.
def example_func(): return ('a', 'b', 'c') first = example_func()[0] print(first) # 👉️ 'a'
If you access a tuple at an index out of bounds, you'd get an IndexError
.
You can use a try/except
statement if you need to handle the error.
my_tuple = ('a', 'b', 'c') try: print(my_tuple[100]) except IndexError: # 👇️ this runs print('Index 100 is not present in the tuple')
The example catches the IndexError
that is thrown if the tuple index is out of
bounds.
You can also directly unpack the items from the tuple into variables.
a, b, c = ('one', 'two', 'three') print(a) # 👉️ one print(b) # 👉️ two print(c) # 👉️ three
When unpacking from a tuple, each variable declaration counts for a single item.
Make sure to declare exactly as many variables as there are items in the tuple.
a, b, c, d = ('one', 'two', 'three', 'four') print(a) # 👉️ one print(b) # 👉️ two print(c) # 👉️ three print(d) # 👉️ four
If you try to unpack more or less values than there are in the tuple, you would get an error.
# ⛔️ ValueError: too many values to unpack (expected 2) a, b = ('one', 'two', 'three')
ValueError
.If you don't need to store a certain value, use an underscore for the variable's name.
a, _, c = ('one', 'two', 'three') print(a) # 👉️ one print(c) # 👉️ three
When you use an underscore for a variable's name, you indicate to other developers that this variable is just a placeholder.
You can use as many underscores as necessary when unpacking values.
a, _, _, d = ('one', 'two', 'three', 'four') print(a) # 👉️ one print(d) # 👉️ four
This is needed because it's not valid syntax to have one comma after another.
# ⛔️ SyntaxError: invalid syntax a, , , d = ('one', 'two', 'three', 'four')