Spring Deals - hours only!Up to 70% off on all courses and bundles.-Close
Iterating over a list
3. Iterating over list elements
Modifying lists
Working with multiple lists


Good job! Let's start with the most basic list technique: iterating over list elements. We often iterate over lists to compute a certain metric based on all the elements. In Python, for loops are typically used for this purpose.

In our example, Mark decided to track the amount of time he stayed in bed. Each element in the sleep_durations list represents the number of minutes he slept on a single day. We'll find Mark's average sleep duration value. Take a look:

sleep_durations = [368, 690, 426, 494, 445, 690, 423, 534, 606, 390]
sleep_durations_sum = 0
sleep_durations_count = 0
for duration in sleep_durations:
  sleep_durations_count += 1
  sleep_durations_sum += duration
avg_sleep_duration = sleep_durations_sum / sleep_durations_count

In such problems, we typically create a temporary variable before iterating over the list. In this case, we defined two variables: sleep_durations_sum and sleep_durations_count, which are initially zero. Inside the for loop, we update both variables as we iterate over the list.

The average value is obtained by dividing the sum by the count.


Martha's monthly spending falls into three categories:

  1. low: below 2000.0
  2. medium: between 2000.0 and 3000.0
  3. high: above 3000.0

Analyze monthly_spendings; create low, medium, and high variables and print the following sentence:

Martha's spending was low for {x} months, medium for {y} months and high for {z} months.

Stuck? Here's a hint!

You will need three temporary variables: low, medium, and high. Inside a for loop, decide which variable should be incremented.