Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Recap
Tuples as return types in functions
Tuples as records
List of tuples
11. Iterating over lists of tuples
Summary

Instruction

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).

Exercise

Create a function named find_mean_salary(people_list) which, given a list of tuples in the format shown in the template code, returns the average salary among all people in the list.

Stuck? Here's a hint!

Create a temporary variable named sum. Iterate over the list and add the salary of each person to the sum. Then, return the sum divided by the number of elements in the list.