Great! Once we have a list of tuples, we can write various functions that operate on such lists. Take a look at an example:
cars_to_sell = [
('Volvo', 18000, 137000),
('BMW', 23000, 80000),
('Opel', 12000, 75000),
('Ford', 14500, 100000)
]
def find_cheapest_car(car_list):
current_cheapest = car_list[0]
for car in car_list:
if car[1] < current_cheapest[1]:
current_cheapest = car
return current_cheapest
find_cheapest_car(cars_to_sell)
In the code above, we create a temporary variable named current_cheapest
, which initially points to the first car tuple in the list. Then, we iterate over the list and we check if the price of the current car (car[1]
) is less than the current cheapest price (current_cheapest
).
Note that we combine list and tuple skills here. We iterate over car_list
using a for
loop (a list technique), but we also access tuple elements using square brackets (a tuple technique).