Python | Combining two sorted lists
Many a times we encounter a problem where we wish to use the merge function of merge sort and is a classical problem that occurs many times while doing competitive programming. This type of problem when known shorter and compact way to perform them are always quite handy.
Let’s discuss certain ways of combining two sorted list in Python.
Method #1 : Naive Method
Merge operation of merge sort can be performed using the naive method which has also been discussed earlier. We check for the smaller of two element on the current index and increment the index of the list whose no. is encountered. When either of the list gets exhausted, the other list is appended to the end of merged list.
# Python3 code to demonstrate # to combine two sorted list # using naive method
# initializing lists test_list1 = [1, 5, 6, 9, 11] test_list2 = [3, 4, 7, 8, 10]
# printing original lists print ("The original list 1 is : " + str(test_list1)) print ("The original list 2 is : " + str(test_list2))
# using naive method # to combine two sorted lists size_1 = len(test_list1) size_2 = len(test_list2)
res = [] i, j = 0, 0
while i < size_1 and j < size_2: if test_list1[i] < test_list2[j]: res.append(test_list1[i]) i += 1
else: res.append(test_list2[j]) j += 1
res = res + test_list1[i:] + test_list2[j:]
# printing result print ("The combined sorted list is : " + str(res)) |
Output:
The original list 1 is : [1, 5, 6, 9, 11] The original list 2 is : [3, 4, 7, 8, 10] The combined sorted list is : [1, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Method #2 : Using sorted()
This function can be used to perform this task in just a 1 line but will take more time internally. It may have more time complexity as we append one list to another and again sort the resultant list. Should be used if we need to save the coding time.
# Python3 code to demonstrate # to combine two sorted list # using sorted()
# initializing lists test_list1 = [1, 5, 6, 9, 11] test_list2 = [3, 4, 7, 8, 10]
# printing original lists print ("The original list 1 is : " + str(test_list1)) print ("The original list 2 is : " + str(test_list2))
# using sorted() # to combine two sorted lists res = sorted(test_list1 + test_list2)
# printing result print ("The combined sorted list is : " + str(res)) |
Output: The original list 1 is : [1, 5, 6, 9, 11] The original list 2 is : [3, 4, 7, 8, 10] The combined sorted list is : [1, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Method #3 : Using heapq.merge()
Python also offers the inbuilt function to perform this particular task and performs the similar working in background as merge in naive method and should be used when wanting to deal with this kind of problem.
# Python3 code to demonstrate # to combine two sorted list # using heapq.merge() from heapq import merge
# initializing lists test_list1 = [1, 5, 6, 9, 11] test_list2 = [3, 4, 7, 8, 10]
# printing original lists print ("The original list 1 is : " + str(test_list1)) print ("The original list 2 is : " + str(test_list2))
# using heapq.merge() # to combine two sorted lists res = list(merge(test_list1, test_list2))
# printing result print ("The combined sorted list is : " + str(res)) |
Output: The original list 1 is : [1, 5, 6, 9, 11] The original list 2 is : [3, 4, 7, 8, 10] The combined sorted list is : [1, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Article Tags :
Python
Python Programs
Python list-programs
Read Full Article
Join / Merge two lists in python using + operator
In python, we can use the + operator to merge the contents of two lists into a new list. For example,
We can use + operator to merge two lists i.e.
# List of strings list_1 = ["This" , "is", "a", "sample", "program"] # List of ints list_2 = [10, 2, 45, 3, 5, 7, 8, 10] # Merge two lists final_list = list_1 + list_2 print('Merged List:') print(final_list)Output:
Merged List: ['This', 'is', 'a', 'sample', 'program', 10, 2, 45, 3, 5, 7, 8, 10]It returned a new concatenated lists, which contains the contents of both list_1 and list_2. Whereas, list_1 and list_2 remained same as original.
Join / Merge two lists in python using list.extend()
In the previous example, we created a new list containing the contents of the both the lists. But what if we want to extend any existing list? We can extend any existing list by concatenating the contents of any other lists to it using the extend() function of list i.e.
list.extend(anotherList)list.extend() makes a list longer by appending the elements of another list at the end of the calling list object. For example,
# List of strings list_1 = ["This" , "is", "a", "sample", "program"] # List of ints list_2 = [10, 2, 45, 3, 5, 7, 8, 10] # Makes list1 longer by appending the elements of list2 at the end. list_1.extend(list_2) print('Merged List:') print(list_1)Output
Merged List: ['This', 'is', 'a', 'sample', 'program', 10, 2, 45, 3, 5, 7, 8, 10]It extended the list_1 by adding the contents of list_2 at the end of list_1.
Combine Python Lists
The easiest way to combine Python lists is to use either list unpacking or the simple + operator.
Let’s take a look at using the + operator first, since it’s syntactically much simpler and easier to understand. Let’s see how we can combine two lists:
# Merge Two Lists list1 = ['datagy', 'is', 'a', 'site'] list2 = ['to', 'learn', 'python'] list3 = list1 + list2 print(list3) # Returns: ['datagy', 'is', 'a', 'site', 'to', 'learn', 'python']We can see here that when we print out third list that it combines the first and second.
Similarly, we can create a new list by unpacking all items from the lists we want to combine. By using the * operator, we can access all the items in both lists and unpack them into a third.
Let’s see what this would look like:
# Merge Two Lists list1 = ['datagy', 'is', 'a', 'site'] list2 = ['to', 'learn', 'python'] list3 = [*list1, *list2] print(list3) # Returns: ['datagy', 'is', 'a', 'site', 'to', 'learn', 'python']In the next section, you’ll learn how to combine two lists in Python in an alternating fashion, using the Python zip() function.
Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!
Combine Python Lists Alternating Using Zip
When you combine Python lists, you may want to add items in an alternating method. For example, you may want to add the first item from both lists, then the second item, and so on.
In order to this, we can use the Python zip() function. The zip function iterates over multiple items sequentially, allowing us to access the items in order.
Let’s see how we can use the zip() function to combine Python lists in an alternating fashion:
# Merge Two Lists in Alternating Fashion list1 = ['1a', '2a', '3a'] list2 = ['1b', '2b', '3b'] list3 = [item for sublist in zip(list1, list2) for item in sublist] print(list3) # Returns: ['1a', '1b', '2a', '2b', '3a', '3b']The zip() function creates a zip object, which is technically a generator object. When we turn this back into a list, we access all the items in the generator. Because of this, we can use the function to combine two Python lists in sequential order.
We then use a list comprehension to flatten the zip object. To learn more about how this works, check out my tutorial on flattening lists of lists.
In the next section, you’ll learn how to combine two Python lists without duplicates.
Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.
Python program to merge two lists and sort the merged list
Python Join Two Lists
❮ Python Glossary
Join Two Lists
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
Example
Join two list:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Another way to join two lists are by appending all the items from list2 into list1, one by one:
Example
Append list2 into list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Or you can use the extend() method, which purpose is to add elements from one list to another list:
Example
Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Merging Lists in Python
Let’s learn about different ways to merge the lists in python.
Merging List in Python
List:
Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might…