Merge Two Sorted Lists – Python

The task is to merge two sorted lists into a single sorted list. For example, given the lists [1, 3, 5] and [2, 4, 6], the output should be [1, 2, 3, 4, 5, 6].

def merge_sorted_lists(list1, list2):
    merged_list = []
    i, j = 0, 0
    
    while i < len(list1) and j < len(list2):
        if list1[i] < list2[j]:
            merged_list.append(list1[i])
            i += 1
        else:
            merged_list.append(list2[j])
            j += 1
    
    # Append any remaining elements
    merged_list.extend(list1[i:])
    merged_list.extend(list2[j:])
    
    return merged_list

# Example
result = merge_sorted_lists([1, 3, 5], [2, 4, 6])
print(result)  # Output: [1, 2, 3, 4, 5, 6]

The function merge_sorted_lists is structured as follows:

  1. Initialization: It initializes an empty list to hold the merged results and two indices to track the current position in each input list.
  2. While Loop: The loop continues until one of the lists is fully traversed. Inside the loop, it compares the current elements of both lists and appends the smaller one to the merged list.
  3. Appending Remaining Elements: After the loop, any remaining elements from either list are appended to the merged list.
  4. Return Statement: Finally, the merged list is returned.