Open In App

Python | Combining two sorted lists

Last Updated : 02 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Many times we encounter a problem where we wish to use the merge function of merge sort which is a classical problem that occurs many times while doing competitive programming. This type of problem when the own shorter and more compact ways to perform them are always quite handy. Let’s discuss certain ways of combining two sorted lists 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 elements on the current index and increment the index of the list whose no. is encountered. When either of the lists gets exhausted, the other list is appended to the end of the merged list. 

Python3




# 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]

Time Complexity: O(n), where n is the total number of elements in both lists.
Auxiliary Space: O(n), as a new list ‘res’ is created to store the combined sorted list.

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




# 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]

Time Complexity: O(nlogn)
Auxiliary Space: O(n), where n is the total number of elements in both lists combined, as sorted() creates a new list to store the sorted elements.

Method #3: Using heapq.merge()

Python also offers the inbuilt function to perform this particular task and performs similar work in the background as merge in naive method and should be used when wanting to deal with this kind of problem.

Python3




# 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]

Time Complexity: O(NlogN), where N is the total number of elements in both lists.
Auxiliary Space: O(N), where N is the total number of elements in both lists.

Method #4 : Using extend() and sort() methods

Python3




# Python3 code to demonstrate
# to combine two sorted list
 
# 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))
 
test_list1.extend(test_list2)
test_list1.sort()
 
# printing result
print("The combined sorted list is : " + str(test_list1))


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]

Time Complexity: O(nlogn), where n is the total number of elements in both lists. 
Auxiliary Space: O(n), where n is the total number of elements in both lists. 

Method #5 :  Using numpy

To install numpy, you can use the pip package manager by running the following command:

pip install numpy

You can use the numpy library to combine two sorted lists in Python. The numpy library provides a function called concatenate() which can be used to combine two or more arrays into a single array.

Here is an example of how you can use the numpy library to combine two sorted lists:

Python3




import numpy as np
 
# Input lists
test_list1 = [1, 5, 6, 9, 11]
test_list2 = [3, 4, 7, 8, 10]
 
# Converting lists to numpy arrays
array1 = np.array(test_list1)
array2 = np.array(test_list2)
 
# use the concatenate function to combine the arrays
combined_array = np.concatenate((array1, array2))
 
# Sorting the combined array
sorted_combined_array = np.sort(combined_array)
 
# Converting the sorted array back to a list
res = sorted_combined_array.tolist()
 
# Print the result
print("The combined sorted list is : " + str(res))


Output: 

The combined sorted list is : [1, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Time Complexity: O(Nlog(N)) due to the use of the sort() function. 
Auxiliary Space: O(N), since it involves creating a new array of size n to hold the combined and sorted elements.

Approach: Using itertools.chain() and sorted()

Algorithm:

  1. Import itertools library
  2. Initialize two sorted lists
  3. Use itertools.chain() method to merge both lists.
  4. Use the sorted() method to sort the merged list.
  5. Print the sorted and merged list.

Python3




# Python3 code to demonstrate
# to combine two sorted list
# using itertools.chain() and sorted()
 
# Importing required libraries
import itertools
 
# Initializing lists
lst1 = [1, 5, 6, 9, 11]
lst2 = [3, 4, 7, 8, 10]
 
# Printing original lists
print("The original list 1 is : " + str(lst1))
print("The original list 2 is : " + str(lst2))
 
# Combining two sorted lists
# using itertools.chain() and sorted() function
merged_list = sorted(itertools.chain(lst1, lst2))
 
# Printing the result
print("The combined sorted list is : " + str(list(merged_list)))


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]

Time Complexity:  O(1), as it only creates an iterator and does not copy the elements. The time complexity of sorted() method is O(nlogn) where n is the total number of elements in the merged list. Thus, the overall time complexity of this approach is O(nlogn).
Auxiliary Space: O(1), as it only creates an iterator and does not copy the elements. The space complexity of sorted() method is O(n) where n is the total number of elements in the merged list. Thus, the overall space complexity of this approach is O(n).



Previous Article
Next Article

Similar Reads

Combining a one and a two-dimensional NumPy Array
Sometimes we need to combine 1-D and 2-D arrays and display their elements. Numpy has a function named as numpy.nditer(), which provides this facility. Syntax: numpy.nditer(op, flags=None, op_flags=None, op_dtypes=None, order='K', casting='safe', op_axes=None, itershape=None, buffersize=0) Example 1: C/C++ Code # importing Numpy package import nump
2 min read
Python | Combining values from dictionary of list
Given a dictionary of list values, the task is to combine every key-value pair in every combination. Input : {"Name" : ["Paras", "Chunky"], "Site" : ["Geeksforgeeks", "Cyware", "Google"] } Output: [{'Site': 'Geeksforgeeks', 'Name': 'Paras'}, {'Site': 'Cyware', 'Name': 'Paras'}, {'Site': 'Google', 'Name': 'Paras'}, {'Site': 'Geeksforgeeks', 'Name':
2 min read
Python | Combining tuples in list of tuples
Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways in which this can be performed. Method #1: Using
7 min read
Python program to check whether number formed by combining all elements of the array is palindrome
Given an array arr[], the task is to combine all the elements in the array sequentially and check if it is a palindrome. Examples: Input: arr[] ={1 , 69 , 54 , 45 , 96 , 1} Output: palindrome Explanation: The number formed by combining all the elements is "1695445961" which is a palindrome Input: arr[] ={2 , 73 , 95 , 59 , 96 , 2} Output: not palin
4 min read
How to Zip two lists of lists in Python?
The normal zip function allows us the functionality to aggregate the values in a container. But sometimes, we have a requirement in which we require to have multiple lists and containing lists as index elements and we need to merge/zip them together. This is quite uncommon problem, but solution to it can still be handy. Let's discuss certain ways i
7 min read
Combining multiple columns in Pandas groupby with dictionary
Let' see how to combine multiple columns in Pandas using groupby with dictionary with the help of different examples. Example #1: # importing pandas as pd import pandas as pd # Creating a dictionary d = {'id':['1', '2', '3'], 'Column 1.1':[14, 15, 16], 'Column 1.2':[10, 10, 10], 'Column 1.3':[1, 4, 5], 'Column 2.1':[1, 2, 3], 'Column 2.2':[10, 10,
2 min read
Combining DataFrames with Pandas
Pandas DataFrame consists of three principal components, the data, rows, and columns. To combine these DataFrames, pandas provides multiple functions like concat() and append(). Method #1: Using concat() method Initially, creating two datasets and converting them into dataframes. C/C++ Code # import required module import pandas as pd # making a da
2 min read
Creating a sorted merged list of two unsorted lists in Python
We need to take two lists in Python and merge them into one. Finally, we display the sorted list. Examples: Input : list1 = [25, 18, 9, 41, 26, 31] list2 = [25, 45, 3, 32, 15, 20] Output : [3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45] Input : list1 = ["suraj", "anand", "gaurav", "aman", "kishore"] list2 = ["rohan", "ram", "mohan", "priya", "komal"
1 min read
Python Program For Finding Intersection Of Two Sorted Linked Lists
Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed.  Example:  Input: First linked list: 1->2->3->4->6 Second linked list be 2->4->6->8, Output: 2->4->6. The elements 2, 4, 6 are common in
4 min read
Python Program To Merge Two Sorted Lists (In-Place)
Given two sorted lists, merge them so as to produce a combined sorted list (without using extra space).Examples: Input: head1: 5->7->9 head2: 4->6->8 Output: 4->5->6->7->8->9 Explanation: The output list is in sorted order. Input: head1: 1->3->5->7 head2: 2->4 Output: 1->2->3->4->5->7 Explanation: The output list is in sorted order. Recommended: Pl
5 min read
Practice Tags :