Last updated: Apr 9, 2024
Reading timeยท5 min
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
.
# โ 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']
We used an index of 1
to get the second element of a tuple.
0
, the second an index of 1
, etc.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
.
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.
my_tuple = ('bobby',) try: second_item = my_tuple[1] except IndexError: # ๐๏ธ this runs print('The 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.
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.
If you need to get the Nth element of each tuple in a list, use a list comprehension.
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) # ๐๏ธ ['!', '@', '#']
We used a list comprehension to get a new list that contains the Nth element of each tuple.
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.
for
loopThis is a three-step process:
for
loop to
iterate over the list of tuples.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]
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.
map()
Alternatively, you can use the map()
function.
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]
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.
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.
zip()
You can also use the zip()
function to get the Nth element from a list of
tuples.
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)
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.
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()
.
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.
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.
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']
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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: