Python: Combine two given sorted lists using heapq module
Python List: Exercise - 152 with Solution
Write a Python program to combine two sorted lists using the heapq module.
Sample Solution:
Python Code:
# Import the 'merge' function from the 'heapq' module, which is used to merge two sorted lists.
from heapq import merge
# Create two sorted lists 'nums1' and 'nums2'.
nums1 = [1, 3, 5, 7, 9, 11]
nums2 = [0, 2, 4, 6, 8, 10]
# Print a message indicating the original sorted lists.
print("Original sorted lists:")
print(nums1)
print(nums2)
# Print a message indicating that the two sorted lists are being merged.
print("\nAfter merging the said two sorted lists:")
# Use the 'merge' function to merge the two sorted lists, convert the result to a list, and print it.
print(list(merge(nums1, nums2)))
Sample Output:
Original sorted lists: [1, 3, 5, 7, 9, 11] [0, 2, 4, 6, 8, 10] After merging the said two sorted lists: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Flowchart:
Python Code Editor:
Previous: Write a Python program to find the maximum and minimum values in a given list within specified index range.
Next: Write a Python program to check if a given element occurs at least n times in a list.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/list/python-data-type-list-exercise-152.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics