So, how can we actually modify list elements? We need to use yet another type of for
loop. Look closely at the example below:
sleep_durations = [368, 690, 426, 494, 445, 690, 423, 534, 606, 390]
for i in range(len(sleep_durations)):
sleep_durations[i] -= 20
print(sleep_durations)
Result:
[348, 670, 406, 474, 425, 670, 403, 514, 586, 370]
This time, we don't iterate over the list. Instead, we iterate over the indexes of the list using a temporary variable named i
, whose values are generated by the range(...)
function. The range(len(sleep_durations))
expression returns all integer values from 0
(inclusive) to len(sleep_durations)
(exclusive). That is, it returns all valid indexes of the sleep_durations
list.
Inside the loop, we use square brackets to access the i
-th element of the list, and we change that element's value. Mark's sleep duration values have now been updated correctly.