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
List 1: [10, 20, 30] List 2: [40, 50, 60] Merged list: [10, 20, 30, 40, 50, 60]
How it works
mergedstarts as an empty list.- The first loop appends every element of
list1, and the second loop appends every element oflist2after them. - The two original lists are not changed, because the elements are copied into a new list.
- The merged list has
len(list1) + len(list2)elements, six here.
Other ways to write it
Using +, unpacking and extend()
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises