Cover Image for How to Merge and Sort Two Lists in Python
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:

  1. list1 and list2 are the two lists you want to merge and sort.
  2. We merge the lists by using the + operator to concatenate list1 and list2, resulting in merged_list.
  3. We use the sorted() function to sort the merged_list in ascending order. The sorted() function returns a new list with the sorted elements, leaving the original list unchanged.
  4. Finally, we print the sorted_merged_list, which contains the sorted elements of both list1 and list2.

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.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS