Python Program to Merge Two Lists and Sort it

PythonServer Side ProgrammingProgramming

When it is required to merge two lists and sort them, a method can be defined that sorts the list using ‘sort’ method.

Below is the demonstration of the same −

Example

 Live Demo

def merge_list(list_1, list_2):
   merged_list = list_1 + list_2
   merged_list.sort()
   return(merged_list)

list_1 = [20, 18, 9, 51, 48, 31]
list_2 = [28, 33, 3, 22, 15, 20]
print("The first list is :")
print(list_1)
print("The second list is :")
print(list_2)
print(merge_list(list_1, list_2))

Output

The first list is :
[20, 18, 9, 51, 48, 31]
The second list is :
[28, 33, 3, 22, 15, 20]
[3, 9, 15, 18, 20, 20, 22, 28, 31, 33, 48, 51]

Explanation

  • A method named ‘merge_list’ is defined that takes two lists as parameters.

  • The two lists are concatenated using the ‘+’ operator.

  • It is assigned to a variable.

  • The sort method is used to sort the final result.

  • Outside the method, two lists are defined, and displayed on the console.

  • The method is called by passing these two lists.

  • The output is displayed on the console.

raja
Published on 19-Apr-2021 11:01:24
Advertisements