Can i have a nice explenation of what this lines of code are doing? -(data structures related )

I am in the middle of training a knowledge i got and redoing some exercise to keep the information good in my head.

Im in an exercise of creating a function, that its target is iterating over 2 lists in the same time, and getting data from them into one list, that i need to return as the target output. Now, i already finished the exercise, just cant understand 2 lines at the end that got to be in there in order for me to pass the exercise. I am doing everything else fine only dont understand the necessity of those 2 lines of code. Would appreciate help in understanding the meaning of those in our words, and what they simply do, and why are they there simply. :

lets say we have an example 2 lists:

list1 = [1, 3, 5, 7, 9]
list2 = [1, 2, 3, 6, 8, 9, 10]

def get_sorted_union(list1, list2):
  i, j = 0, 0
  list_to_return = []
  while i < len(list1) and j < len(list2):
    if list1[i] > list2[j]:
      j += 1
    elif list1[i] < list2[j]:
      i += 1
      i += 1
      j += 1
  list_to_return += list1[i:] #Those are the 2 lines i cant understand why they exist. v
  list_to_return += list2[j:]
  return list_to_return

>Solution :

The last two lines are adding the remainder of the input lists to the output.

This is important when your input lists are of different length. For e.g.

list1 = [1,4,5]
list2 = [2]

Now, when the code reaches those lines, i = 1 and j = 1. Your list_to_return only has [1,2], but you want to add the remaining elements from list1 [4,5] to this list as well

Leave a Reply