merge lists python code example

Example 1: Merge Sort python

def merge_sort(arr):
    # The last array split
    if len(arr) <= 1:
        return arr
    mid = len(arr) // 2
    # Perform merge_sort recursively on both halves
    left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:])

    # Merge each side together
    return merge(left, right, arr.copy())


def merge(left, right, merged):

    left_cursor, right_cursor = 0, 0
    while left_cursor < len(left) and right_cursor < len(right):
      
        # Sort each one and place into the result
        if left[left_cursor] <= right[right_cursor]:
            merged[left_cursor+right_cursor]=left[left_cursor]
            left_cursor += 1
        else:
            merged[left_cursor + right_cursor] = right[right_cursor]
            right_cursor += 1
            
    for left_cursor in range(left_cursor, len(left)):
        merged[left_cursor + right_cursor] = left[left_cursor]
        
    for right_cursor in range(right_cursor, len(right)):
        merged[left_cursor + right_cursor] = right[right_cursor]

    return merged

Example 2: how to combine two arrays in python

# concatenate 2 numpy arrays: row-wise
>np.concatenate((array2D_1, array2D_2))
 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [10, 11, 12],
       [13, 14, 15],
       [16, 17, 18]])

Example 3: python concatenate lists

a = [1, 2, 3]
b = [4, 5]

# method 1:
c = a + b # forms a new list with all elements
print(c) # [1, 2, 3, 4, 5]

# method 2:
a.extend(b) # adds the elements of b into list a
print(a) # [1, 2, 3, 4, 5]

Example 4: how to combine two lists in python

listone = [1,2,3]
listtwo = [4,5,6]

joinedlist = listone + listtwo

Example 5: python how to add one list to another list

# Basic syntax:
first_list.append(second_list) # Append adds the the second_list as an
#	element to the first_list
first_list.extend(second_list) # Extend combines the elements of the 
#	first_list and the second_list

# Note, both append and extend modify the first_list in place

# Example usage for append:
first_list = [1, 2, 3, 4, 5]
second_list = [6, 7, 8, 9]
first_list.append(second_list)
print(first_list)
--> [1, 2, 3, 4, 5, [6, 7, 8, 9]]

# Example usage for extend:
first_list = [1, 2, 3, 4, 5]
second_list = [6, 7, 8, 9]
first_list.extend(second_list)
print(first_list)
--> [1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 6: add two list in python

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list1.extend(list2)
print(list1)