Python Program to Merge Two Lists and Sort it

This is a Python Program to merge two lists and sort it.

Problem Description

The program takes two lists, merges them and sorts the merged list.

Problem Solution

1. Take in the number of elements for the first list and store it in a variable.
2. Take in the elements of the list one by one.
3. Similarly, take in the elements for the second list also.
4. Merge both the lists using the ‘+’ operator and then sort the list.
5. Display the elements in the sorted list.
6. Exit.

Program/Source Code

Here is source code of the Python Program to merge two lists and sort it. The program output is also shown below.

a=[]
c=[]
n1=int(input("Enter number of elements:"))
for i in range(1,n1+1):
    b=int(input("Enter element:"))
    a.append(b)
n2=int(input("Enter number of elements:"))
for i in range(1,n2+1):
    d=int(input("Enter element:"))
    c.append(d)
new=a+c
new.sort()
print("Sorted list is:",new)
Program Explanation

1. User must enter the number of elements for the first list and store it in a variable.
2. User must then enter the elements of the list one by one using a for loop and store it in a list.
3. User must similarly enter the elements of the second list one by one.
4. The ‘+’ operator is then used to merge both the lists.
5. The sort function then sorts the list in ascending order.
6. The sorted list is then printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter number of elements:5
Enter element:10
Enter element:20
Enter element:35
Enter element:55
Enter element:71
Enter number of elements:2
Enter element:5
Enter element:37
Sorted list is: [5, 10, 20, 35, 37, 55, 71]
 
Case 2:
Enter number of elements:3
Enter element:2
Enter element:4
Enter element:8
Enter number of elements:3
Enter element:2
Enter element:4
Enter element:0
Sorted list is: [0, 2, 2, 4, 4, 8]

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Note: Join free Sanfoundry classes at Telegram or Youtube

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.