Python program to merge two lists and sort it

Python 3 program to Merge two lists and sort it :

Write a Python 3 program to merge two lists, and sort the final list. Take inputs for both lists from the user. Let’s take a look into the algorithm first :

The algorithm to merge two lists and sort it :

1. Create two empty lists.
2. First, take the total number for the first list from the user.
3. Using a loop, read all the numbers for the first list and append it to the list.
4. Similarly, take the total number for the second list and read all numbers for the second list.
5. Append both lists and save it in a different variable.
6. Sort the final list.
7. Print all lists.

Python3 Program :

first_list = []
second_list = []

#get total count for the first list
count_first_list = int(input("Enter total numbers of the first list : "))

#take inputs from the user for the first list
for i in range(1,count_first_list+1):
	no = int(input("Enter : "))
	first_list.append(no)

#get total count for the second list
count_second_list = int(input("Enter total numbers of the second list : "))

#take inputs from the user for the second list
for i in range(1,count_second_list+1):
	no = int(input("Enter : "))
	second_list.append(no)

#print first and second list
print("First list : ",first_list)
print("Second list : ",second_list)

#append both list
final_list = first_list + second_list

#sort the final list
final_list.sort()

#print the final sorted list
print("Final list : ",final_list)

Notes :

1. We are using ‘for’ loop to read the numbers for the list.
2. To add an element to a list, ‘append()’ is used.
3. To append both lists, ‘+’ is used.
4. To sort a list, ‘sort()’ is used.

Sample outputs :

#Example 1

Enter total numbers of the first list : 4
Enter : 1
Enter : 3
Enter : 6
Enter : 9
Enter total numbers of the second list : 5
Enter : 100
Enter : 13
Enter : 16
Enter : 2
Enter : 5
First list :  [1, 3, 6, 9]
Second list :  [100, 13, 16, 2, 5]
Final list :  [1, 2, 3, 5, 6, 9, 13, 16, 100]

#Example 2

Enter total numbers of the first list : 3
Enter : 1
Enter : 2
Enter : 3
Enter total numbers of the second list : 3
Enter : 3
Enter : 4
Enter : 5
First list :  [1, 2, 3]
Second list :  [3, 4, 5]
Final list :  [1, 2, 3, 3, 4, 5]

#Example 3

Enter total numbers of the first list : 4
Enter : 4
Enter : 6
Enter : 8
Enter : 8
Enter total numbers of the second list : 1
Enter : -1
First list :  [4, 6, 8, 8]
Second list :  [-1]
Final list :  [-1, 4, 6, 8, 8]

Leave a Reply