Sort a List in Python
In Python, you can sort a list using the sort() method or the sorted() function.
Using sort() method
The sort() method sorts the list in place, modifying the original list. It doesn’t return a new list.
my_list = [50, 10, 40, 20, 30]
my_list.sort()
print(my_list) # Output: [10, 20, 30, 40, 50]
To sort the list in descending order, you can use the reverse parameter.
my_list = [50, 10, 40, 20, 30]
my_list.sort(reverse=True)
print(my_list) # Output: [50, 40, 30, 20, 10]
The sort() method is faster than sorted() function because it modifies the list in place, avoiding the overhead of creating a new list.
Using sorted() function
The sorted() function returns a new sorted list without modifying the original list.
my_list = [50, 10, 40, 20, 30]
sorted_list = sorted(my_list)
print(sorted_list) # Output: [10, 20, 30, 40, 50]
To sort a list in descending order, you can use the reverse parameter with the value True.
my_list = [50, 10, 40, 20, 30]
sorted_list = sorted(my_list, reverse=True)
print(sorted_list) # Output: [50, 40, 30, 20, 10]
Sorting with a key
Both sort() and sorted() support a key parameter, which specifies a function that is applied to each element in the list to determine the sorting criteria.
my_list = ["banana", "apple", "watermelon", "kiwi"]
# Sort by word length
my_list.sort(key=len)
print(my_list) # Output: ['kiwi', 'apple', 'banana', 'watermelon']
You can also do the same with the sorted() function.
my_list = ["banana", "apple", "watermelon", "kiwi"]
# Sort by word length
new_list = sorted(my_list, key=len)
print(new_list) # Output: ['kiwi', 'apple', 'banana', 'watermelon']
Example: Sort a List of Strings Case-insensitively
fruits = ["Banana", "apple", "Orange", "mango"]
fruits.sort(key=str.lower)
print(fruits) # Output: ['apple', 'Banana', 'mango', 'Orange']