
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Combine Two Sorted Lists in Python
Lists are one of the most extensively used python data structures. In this article we will see how to combine the elements of two lists and produce the final output in a sorted manner.
With + and sorted
The + operator can join the elements of two lists into one. Then we apply the sorted function which will sort the elements of the final list created with this combination.
Example
listA = ['Mon', 'Tue', 'Fri'] listB = ['Thu','Fri','Sat'] # Given lists print("Given list A is : ",listA) print("Given list B is : ",listB) # Add and sort res = sorted(listA + listB) # Result print("The combined sorted list is : \n" ,res)
Output
Running the above code gives us the following result −
Given list A is : ['Mon', 'Tue', 'Fri'] Given list B is : ['Thu', 'Fri', 'Sat'] The combined sorted list is : ['Fri', 'Fri', 'Mon', 'Sat', 'Thu', 'Tue']
With merge
The merge function from heapq module can combine the elements of two lists. Then we apply the sorted function to get the final output.
Example
from heapq import merge listA = ['Mon', 'Tue', 'Fri'] listB = ['Thu','Fri','Sat'] # Given lists print("Given list A is : ",listA) print("Given list B is : ",listB) # Merge res = list(merge(listA,listB)) # Result print("The combined sorted list is : \n" ,sorted(res))
Output
Running the above code gives us the following result −
Given list A is : ['Mon', 'Tue', 'Fri'] Given list B is : ['Thu', 'Fri', 'Sat'] The combined sorted list is : ['Fri', 'Fri', 'Mon', 'Sat', 'Thu', 'Tue']
Advertisements