Perfect! What happens when we want to compare elements in two lists of different lengths? In such cases, we need to think carefully about the indexes of both lists. Python can throw an IndexError
if we try to access an element that is beyond the bounds of a list.
mark_sleep_durations = [368, 690, 426, 494, 445, 690, 423, 534, 606, 390]
kate_sleep_durations = [546, 562, 474, 440, 299]
mark_longer_count = 0 # mark_longer_count stores a number of times when Mark slept longer.
for i in range(min(len(mark_sleep_durations), len(kate_sleep_durations))):
if mark_sleep_durations[i] > kate_sleep_durations[i]:
mark_longer_count += 1
print(mark_longer_count)
One way of dealing with lists of different lengths is by iterating over the indexes of the shorter list. Note that we changed
for i in range(len(mark_sleep_durations)):
to
for i in range(min(len(mark_sleep_durations), len(kate_sleep_durations))):
We will only iterate as many times as there are elements in a shorter list. In this way, we prevent IndexError
s.