Skip to content
The Chat Archive
gpt-4-0613· OpenAI Arena Human Preference 55K

Write a python function to merge two sorted lists into one sorted list.

  1. User

    Write a python function to merge two sorted lists into one sorted list.

  2. Assistant

    Sure, here is a simple Python function that merges two sorted lists into one sorted list:

    def merge_sorted_lists(list1, list2):
        # Initialize the result list
        result = []
        
        # Initialize two indices to keep track of current element in both lists
        i = j = 0
    
        # Merge elements of both lists until one list exhausts
        while i < len(list1) and j < len(list2):
            if list1[i] <= list2[j]:
                result.append(list1[i])
                i += 1
            else:
                result.append(list2[j])
                j += 1
    
        # If there are remaining elements in list1, append them to result
        while i < len(list1):
            result.append(list1[i])
            i += 1
    
        # If there are remaining elements in list2, append them to result
        while j < len(list2):
            result.append(list2[j])
            j += 1
    
        return result
    

    You can use this function to merge two sorted lists like this:

    list1 = [1, 3, 5, 7]
    list2 = [2, 4, 6, 8]
    merged_list = merge_sorted_lists(list1, list2)
    print(merged_list)  # Output: [1, 2, 3, 4, 5, 6, 7, 8]
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.