Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Merge Two Lists and Sort it
When it is required to merge two lists and sort them, Python provides several approaches. You can use list concatenation with the sort() method, or combine merging and sorting in one step using sorted().
Below is the demonstration of the same ?
Method 1: Using List Concatenation and sort()
Example
Define a function that merges two lists and sorts them in-place ?
def merge_list(list_1, list_2):
merged_list = list_1 + list_2
merged_list.sort()
return merged_list
numbers_1 = [20, 18, 9, 51, 48, 31]
numbers_2 = [28, 33, 3, 22, 15, 20]
print("The first list is:")
print(numbers_1)
print("The second list is:")
print(numbers_2)
print("The merged and sorted list is:")
print(merge_list(numbers_1, numbers_2))
The first list is: [20, 18, 9, 51, 48, 31] The second list is: [28, 33, 3, 22, 15, 20] The merged and sorted list is: [3, 9, 15, 18, 20, 20, 22, 28, 31, 33, 48, 51]
Method 2: Using sorted() Function
Example
Use the sorted() function to merge and sort in one step ?
def merge_and_sort(list_1, list_2):
return sorted(list_1 + list_2)
numbers_1 = [20, 18, 9, 51, 48, 31]
numbers_2 = [28, 33, 3, 22, 15, 20]
result = merge_and_sort(numbers_1, numbers_2)
print("Merged and sorted list:", result)
Merged and sorted list: [3, 9, 15, 18, 20, 20, 22, 28, 31, 33, 48, 51]
Method 3: Using extend() Method
Example
Use extend() to add elements from the second list to the first ?
def merge_with_extend(list_1, list_2):
merged_list = list_1.copy() # Create a copy to avoid modifying original
merged_list.extend(list_2)
merged_list.sort()
return merged_list
numbers_1 = [20, 18, 9, 51, 48, 31]
numbers_2 = [28, 33, 3, 22, 15, 20]
result = merge_with_extend(numbers_1, numbers_2)
print("Result using extend():", result)
Result using extend(): [3, 9, 15, 18, 20, 20, 22, 28, 31, 33, 48, 51]
Comparison
| Method | Creates New List? | Modifies Original? | Best For |
|---|---|---|---|
list1 + list2 |
Yes | No | Simple concatenation |
sorted() |
Yes | No | One-step merge and sort |
extend() |
Optional | Optional | Memory-efficient merging |
How It Works
The
+operator concatenates two lists by creating a new list containing all elements.The
sort()method sorts the list in-place, modifying the original list.The
sorted()function returns a new sorted list without modifying the original.The
extend()method adds all elements from one list to another efficiently.
Conclusion
Use sorted(list1 + list2) for a clean one-liner approach. Use extend() with sort() for memory-efficient merging of large lists. All methods preserve the original lists unless you explicitly modify them.
