Python Program to merge and sort two list or array


April 2, 2022, Learn eTutorial
976

In this simple python program, we need to merge and sort two arrays. It is a number-based python program.

For a better understanding of this example, we always recommend you to learn the basic topics of Python programming listed below:

How to merge and sort two arrays?

In this python program, we have to merge and sort two lists. Arrays are a set of elements of the same data type and accessed with the same index. In this python program, we need to initialize and add some elements in two lists or array, and we have to merge those lists and then sort the content of the big list.

The sort() function is the inbuilt function we use here to sort the list. Let us check what we have done to accomplish the task in the python language. After taking the user's input and append the input to a different list or array using  append method in python, we are just adding the list together by a+c then apply the sort function, which is an in-built function in python language to sort the elements of the new list. And finally, print the list.

ALGORITHM

STEP 1: Initialize two lists or arrays in python in two variables.

STEP 2: Accept the number of elements needed for list 1 from the user and store it in a variable using the input method.

STEP 3: Open a for loop using range method from 1 to the number of elements entered by the user to accept each element in the list.

STEP 4: Use the append operator to add the user input elements to the list.

STEP 5: Accept the number of terms for the second list.

STEP 6: Using for loop and append operator accept and add the elements to the second list.

STEP 7: Now, we are merging the list using + operator as first list + second list.

STEP 8: Apply the sort() function, a built-in function in the python programming language, to sort the merged list elements.

STEP 9: Print the merged and sorted list using the print statement.

Python Source Code

                                          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)
                                      

OUTPUT

Enter number of elements:4
Enter element:1
Enter element:2
Enter element:3
Enter element:5

Enter number of elements:3
Enter element:9
Enter element:8
Enter element:7
Sorted list is: [1, 2, 3, 5, 7, 8, 9]