How do you sort a list in Python?

Python >   Python List >   Python List  

Long Question

250


Answer:

There are several ways to sort a list in Python, depending on your specific requirements.

The most straightforward way to sort a list is to use the built-in sorted function. The sorted function takes a list as an argument and returns a new list containing the elements of the original list, sorted in ascending order:


# Original list
original_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

# Sorted list
sorted_list = sorted(original_list)

print("Original list:", original_list)
print("Sorted list:", sorted_list)

Output:


Original list: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
Sorted list: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

If you need to sort the list in descending order, you can pass the reverse=True argument to the sorted function:


# Sorted list in descending order
sorted_list = sorted(original_list, reverse=True)

print("Sorted list in descending order:", sorted_list)

Output:


Sorted list in descending order: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]

Another way to sort a list is to use the sort method of the list object. The sort method sorts the list in-place and returns None, so you need to call it on the list you want to sort:


# Sort the original list in-place
original_list.sort()

print("Original list:", original_list)

Output:


Original list: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

Just like the sorted function, you can also sort the list in descending order using the sort method by passing the reverse=True argument:


# Sort the original list in-place in descending order
original_list.sort(reverse=True)

print("Original list:", original_list)

Output:


Original list: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]

Note that the sort method modifies the list in-place, so if you need to keep the original list intact, you should use the sorted function instead.


This Particular section is dedicated to Question & Answer only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.