How do I sort a list in Python?
Use the `sort()` method to sort a list in place or the `sorted()` function to return a new sorted list without modifying the original.
Sorting lists in Python can be accomplished using two primary methods: the sort()
method and the sorted()
function. The sort()
method modifies the list in place, while sorted()
returns a new sorted list without changing the original list.
Using sort()
Method
To sort a list in place, you can use:
my_list = [3, 1, 4, 1, 5]
my_list.sort()
print(my_list) # Output: [1, 1, 3, 4, 5]
You can also customize the sorting behavior by providing a key
function and a reverse
boolean argument:
my_list.sort(key=lambda x: -x) # Sort in descending order
Using sorted()
Function
If you want to maintain the original list, use the sorted()
function:
original_list = [3, 1, 4, 1, 5]
sorted_list = sorted(original_list)
print(sorted_list) # Output: [1, 1, 3, 4, 5]
print(original_list) # Output: [3, 1, 4, 1, 5]
The sorted()
function can also accept key
and reverse
parameters for custom sorting. Understanding how to sort lists effectively is crucial for data manipulation and analysis in Python.