
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Combining 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']
- Related Questions & Answers
- Merge Two Sorted Lists in Python
- Merge two sorted linked lists using C++.
- Merge k Sorted Lists in Python
- Python program to create a sorted merged list of two unsorted lists
- Combining two arrays in JavaScript
- Combining two heatmaps in seaborn
- Program to find median of two sorted lists in C++
- Dividing two lists in Python
- Program to merge K-sorted lists in Python
- Adding two Python lists elements
- Intersection of Two Linked Lists in Python
- Concatenate two lists element-wise in Python
- How to compare two lists in Python?
- Merge K sorted linked lists in Java
- Combining two Series into a DataFrame in Pandas
Advertisements