Excellent work! Tuples can also be returned from functions. Take a look:
users = [
('John', 'Smith', 29, 1.85, 'British'),
('Anne', 'Johnson', 27, 1.76, 'American'),
('Alejandro', 'Garcia', 25, 1.80, 'Spanish'),
('Janusz', 'Nowak', 32, 1.84, 'Polish')
]
def get_min_max_height(users):
min_height = users[0][3]
max_height = users[0][3]
for user in users:
if user[3] > max_height:
max_height = user[3]
if user[3] < min_height:
min_height = user[3]
return (min_height, max_height)
get_min_max_height(users)
The code above accepts a list of tuples and returns a tuple with two values: the minimum and maximum height of the users. To access a given tuple in the list, we can use a single pair of square brackets: for example, users[0]
is the first tuple in the list.
Once we have a tuple selected, we can use another pair of square brackets to select a given item from the tuple. Here, users[0][3]
selects the first tuple and then selects the height (the fourth element) for this tuple. The function iterates over the list, checks the height value in each tuple, and updates min_height
or max_height
accordingly. On the last line, we return a new tuple created with (min_height, max_height)
. Naturally, we can store the return value in a variable:
min_max_height = get_min_max_height(users)
Alternatively, you can also unpack the function result into two separate variables:
min_height, max_height = get_min_max_height(users)