Python program to merge two lists and sort it
In this tutorial, we will learn about writing a Python program to merge two lists and then sort it
This tutorial may also be helpful while working on multiple lists.
Python allows merging just by using ‘ + ‘ operator as any number of lists can be merged using this operator. For instance, let us see an example
Merge two lists and then sort it in Python
List_1 = [1,2,3,4,5] List_2 = [6,7,8,9,10]
Above we have two list mentioned as List_1(which contains numbers 1-5)
and the second list is List_2(which contains numbers 6-10) and now using ‘ + ‘ operator
we will combine the two and assign it into the third list which will be named as List_3
List_3 = List_1 + List_2
Now let us print List_3:
You can also use the extend Keyword to merge 2 List which changes one of the List as shown below
that is List_1’s elements all got appended to the List_2 which changes the List_2 which will be reflected as
we print the List_3
List_1 = [1,2,3,4,5] List_2 = [5,6,7,8,9,10] List_2.extend(List_1) List_3 = List_2 print(List_3)
[5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5]
Now our another task is to sort the merged List:
For this, we are free to use the various algorithms built to sort an array of numbers but
Python being a powerful language has a method which sorts the List in an efficient way.
Now above what we see is .sort() changed the entire List_3 .
As a matter of fact Python is a Powerful language it also allows you to Sort the
List without affecting the list using the sorted() function which has got a list as an argument.
Seems amazing…isn’t it Let’s see
Now if you have not used .sort() method enquire about List_3 and what you will find is
List_3 will remain unaffected.