Back-To-School Deals - hours only!Up to 80% off on all courses and bundles.-Close
Recap
Iterating over a list
Modifying lists
Working with multiple lists
14. Merging two sorted lists
Congratulations

Instruction

Very well done! Another typical problem is merging two sorted lists into a common sorted list. Suppose we have sleep duration times for two weeks in two separate, sorted lists:

sleep_durations_week_1 = [301, 346, 378, 410, 420]
sleep_durations_week_2 = [289, 317, 367, 414, 454]

We now want to create a common list containing all values from week 1 and week 2, sorted by amount. Take a look:

i, j = 0, 0
sorted_two_weeks = []
while i < len(sleep_durations_week_1) and j < len(sleep_durations_week_2):
  if sleep_durations_week_1[i] < sleep_durations_week_2[j]:
    sorted_two_weeks.append(sleep_durations_week_1[i])
    i += 1
  else:
    sorted_two_weeks.append(sleep_durations_week_2[j])
    j += 1
sorted_two_weeks += sleep_durations_week_1[i:]
sorted_two_weeks += sleep_durations_week_2[j:]

We use the temporary variables i and j. Here, i represents the current index in sleep_durations_week_1, and j does the same for sleep_durations_week_2.

We create a while loop that continues until the end of either of the two lists. Inside the loop, we compare sleep_durations_week_1[i] and sleep_durations_week_2[j]. If sleep_durations_week_1[i] is smaller, then we add this value to the list and increment i by 1. Otherwise, we add sleep_durations_week_2[j] to the list and increment j by 1.

At some point, either i or j will point to the end of its respective list, but the other variable will still point to some remaining values in the other list. That's why we need to add those remaining elements after the while loop terminates.

merging_sorted_lists merging_sorted_lists

Exercise

Now it's your turn! You are given two lists: one of Martha's monthly spending in 2017 and another of her spending in 2018. Both lists are sorted in descending order. Merge these lists into a new list named all_sorted_spendings. The new list should also be sorted in descending order.

Stuck? Here's a hint!

The solution is very similar to the one in the explanation. Inside the while loop, change the less-than sign to a greater-than sign.