Great! Often when you iterate over a list, you'd like to have an access to both the index of the current element and the value of this element. Python has a useful function named enumerate()
exactly for this purpose. Together with a for
loop, enumerate()
allows you to access both the index and the value while iterating. Look at the example:
sleep_durations = [368, 690, 426, 494, 445, 690, 423, 534, 606, 390]
sleep_durations_sum = 0
sleep_durations_count = 0
for i, duration in enumerate(sleep_durations):
if 0 <= i % 7 <= 4:
sleep_durations_count += 1
sleep_durations_sum += duration
avg_sleep_duration = sleep_durations_sum / sleep_durations_count
print(avg_sleep_duration)
Mark started tracking his sleep duration on Monday. The code above computes Mark's average sleep duration on weekdays (Monday through Friday). The function enumerate(sleep_duration)
for each element in the list sleep_duration
returns an index (we store it in the variable i
) and the value (we use the duration
variable).
Inside the for
loop, we check if the current day is a weekday. Weekdays are stored in the list under indexes 0
to 4
(Monday to Friday in the first week), 7
to 11
(Monday to Friday in the second week), etc. The weekday indexes are between 0
and 4
modulo 7
. This is what the condition 0 <= i % 7 <= 4
checks. Note that Python allows you to use the concise mathematical syntax a < b < c
. In many other programming languages, you have to write the same condition as 0 <= i % 7
and i % 7 <= 4
.