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