Python program to create a sorted merged list of two unsorted lists

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to write a program that merges two lists and prints the resultant list in sorted order. Let's see some examples.

Input:
list_1 = [1, 3, 2, 0, 3]
list_2 = [20, 10, 23, 43, 56, -1]
Output:
[-1, 0, 1, 2, 3, 3, 10, 20, 23, 43, 56]


Input:
list_1 = ["hafeez", "aslan"]
list_2 = ["abc", "kareem", "b"]
Output:
["abc", "aslan", "b", "hafeez", "kareem"]

Let's try to write the code with the following steps.

Algorithm

1. Initialize the lists.
2. Concatenate the two lists using + operator and store the result in a new variable.
3. Sort the resultant list with sort() method of the list.
4. Print the sorted list.

See the code.

Example

 Live Demo

## initializing the lists
list_1 = [1, 3, 2, 0, 3]
list_2 = [20, 10, 23, 43, 56, -1]
## concatenating two lists
new_list = list_1 + list_2
## soring the new_list with sort() method
new_list.sort()
## printing the sorted list
print(new_list)

Output

If you run the above program, you will get the following output.

[-1, 0, 1, 2, 3, 3, 10, 20, 23, 43, 56]

We are executing the same program with different lists.

Example

 Live Demo

## initializing the lists
list_1 = ["hafeez", "aslan"]
list_2 = ["abc", "kareem", "b"]
## concatenating two lists
new_list = list_1 + list_2
## soring the new_list with sort() method
new_list.sort()
## printing the sorted list
print(new_list)

Output

If you run the above program, you will get the following output.

['abc', 'aslan', 'b', 'hafeez', 'kareem']

Conclusion

If you have any doubts regarding the tutorial, mention them in the comment section.

raja
Published on 23-Oct-2019 10:59:29
Advertisements