
147 views
How to Merge and Sort Two Lists in Python
The merge and sort two lists in Python, you can use a combination of the extend()
method to merge the lists and the sorted()
function to sort the resulting merged list. Here’s how you can do it:
# Two lists to merge and sort
list1 = [3, 1, 4]
list2 = [1, 5, 9]
# Merge the lists using the extend method
merged_list = list1 + list2
# Sort the merged list using the sorted function
sorted_merged_list = sorted(merged_list)
print(sorted_merged_list)
In this example:
list1
andlist2
are the two lists you want to merge and sort.- We merge the lists by using the
+
operator to concatenatelist1
andlist2
, resulting inmerged_list
. - We use the
sorted()
function to sort themerged_list
in ascending order. Thesorted()
function returns a new list with the sorted elements, leaving the original list unchanged. - Finally, we print the
sorted_merged_list
, which contains the sorted elements of bothlist1
andlist2
.
The output will be:
[1, 1, 3, 4, 5, 9]
If you want to sort the merged list in descending order, you can use the reverse=True
argument in the sorted()
function like this:
sorted_merged_list = sorted(merged_list, reverse=True)
This will give you the merged list sorted in descending order:
[9, 5, 4, 3, 1, 1]
You can adjust the sorting order based on your specific requirements.