Editor

Python Program to Merge Two Lists

Beginner · Lists

Merging two lists means joining them into one list that holds the elements of the first followed by the elements of the second. This program builds the merged list with a loop, and the alternatives show the quicker built-in ways and how to merge two sorted lists so the result stays sorted.

Program

merge_two_lists.py
list1 = [10, 20, 30] # or: list1 = input("Enter the first list: ").split()
list2 = [40, 50, 60] # or: list2 = input("Enter the second list: ").split()
merged = []
for item in list1:
merged.append(item)
for item in list2:
merged.append(item)
print("List 1:", list1)
print("List 2:", list2)
print("Merged list:", merged)
Output
List 1: [10, 20, 30]
List 2: [40, 50, 60]
Merged list: [10, 20, 30, 40, 50, 60]

How it works

  1. merged starts as an empty list.
  2. The first loop appends every element of list1, and the second loop appends every element of list2 after them.
  3. The two original lists are not changed, because the elements are copied into a new list.
  4. The merged list has len(list1) + len(list2) elements, six here.

Other ways to write it

Using +, unpacking and extend()

Using +, unpacking and extend()
list1 = [10, 20, 30]
list2 = [40, 50, 60]
print("Using +:", list1 + list2)
print("Using unpacking:", [*list1, *list2])
list1.extend(list2) # adds list2 onto the end of list1 itself
print("list1 after extend():", list1)
Output
Using +: [10, 20, 30, 40, 50, 60]
Using unpacking: [10, 20, 30, 40, 50, 60]
list1 after extend(): [10, 20, 30, 40, 50, 60]

+ and [*list1, *list2] make a new list, while extend() changes list1 in place, so pick extend() only when you no longer need the original.

Merging two sorted lists

Merging two sorted lists
a = [1, 4, 7, 10]
b = [2, 3, 8, 12, 15]
merged = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] <= b[j]: # take the smaller front element
merged.append(a[i])
i += 1
else:
merged.append(b[j])
j += 1
merged += a[i:] + b[j:] # one list may have elements left over
print("Merged sorted list:", merged)
Output
Merged sorted list: [1, 2, 3, 4, 7, 8, 10, 12, 15]

This walks both lists at once and always takes the smaller front element, so the result is sorted without sorting it again. It is the merge step of merge sort.

Try it yourself

Merge three lists instead of two, and then print the merged list in sorted order with sorted().

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises