Python – Sort Lists
In Python, you can sort lists in various ways, either in ascending or descending order, and you can choose to modify the list in place or create a new sorted list. Below are the different ways to sort lists in Python:
1. Sorting in Place with sort()
The sort() method sorts the list in place, meaning it modifies the original list directly. By default, it sorts the list in ascending order.
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
# Sort the list in ascending order
my_list.sort()
print(my_list) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
2. Sorting in Descending Order with sort()
You can sort the list in descending order by passing the reverse=True argument to the sort() method.
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
# Sort the list in descending order
my_list.sort(reverse=True)
print(my_list) # Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
3. Sorting and Creating a New List with sorted()
The sorted() function returns a new sorted list, leaving the original list unchanged. By default, it sorts the list in ascending order.
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
# Create a new sorted list
sorted_list = sorted(my_list)
print(sorted_list) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
print(my_list) # Original list remains unchanged
4. Sorting in Descending Order with sorted()
You can use the reverse=True argument with sorted() to sort the list in descending order and create a new list.
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
# Create a new sorted list in descending order
sorted_list_desc = sorted(my_list, reverse=True)
print(sorted_list_desc) # Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
5. Sorting with a Custom Key Using sort() and sorted()
Both the sort() method and the sorted() function allow you to provide a custom sorting key using the key argument. The key argument is a function that extracts a sorting key from each element in the list.
For example, you can sort a list of strings by their length:
my_list = ["apple", "banana", "cherry", "date"]
# Sort by length of the strings
my_list.sort(key=len)
print(my_list) # Output: ['date', 'apple', 'cherry', 'banana']
6. Sorting a List of Tuples by Specific Element
If you have a list of tuples, you can sort the list based on a specific element of the tuple using the key argument.
my_list = [(1, "apple"), (3, "banana"), (2, "cherry")]
# Sort by the first element of the tuple (the number)
my_list.sort(key=lambda x: x[0])
print(my_list) # Output: [(1, 'apple'), (2, 'cherry'), (3, 'banana')]
7. Sorting Lists of Dictionaries
If you have a list of dictionaries, you can sort it by a specific key within the dictionaries.
my_list = [{"name": "apple", "price": 5}, {"name": "banana", "price": 2}, {"name": "cherry", "price": 7}]
# Sort the list by the "price" key
my_list.sort(key=lambda x: x["price"])
print(my_list) # Output: [{'name': 'banana', 'price': 2}, {'name': 'apple', 'price': 5}, {'name': 'cherry', 'price': 7}]
8. Sorting Lists Containing Objects
If you have a list of objects, you can sort them based on an attribute using the key argument. For example, if you have a list of Person objects, you can sort by their age attribute.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
people = [Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35)]
# Sort the list by age
people.sort(key=lambda x: x.age)
for person in people:
print(f"{person.name}: {person.age}")
Output:
Bob: 25
Alice: 30
Charlie: 35
9. Sorting a List of Strings Alphabetically
By default, when you use sort() or sorted() on a list of strings, it sorts them in alphabetical order.
my_list = ["orange", "apple", "banana", "cherry"]
# Sort alphabetically
my_list.sort()
print(my_list) # Output: ['apple', 'banana', 'cherry', 'orange']
10. Sorting a List of Numbers in Reverse Order
You can sort a list of numbers in reverse order by using the reverse=True argument.
my_list = [10, 2, 33, 4, 21, 1]
# Sort in descending order
my_list.sort(reverse=True)
print(my_list) # Output: [33, 21, 10, 4, 2, 1]
Summary:
sort(): Sorts the list in place (modifies the original list).sorted(): Returns a new sorted list without modifying the original.reverse=True: Sorts in descending order.key=: Sort by a custom key (e.g., length of strings, values in tuples).- Sorting a list of dictionaries/objects: Use the
keyargument with a lambda function to sort by specific attributes.
Sorting is an essential feature in Python, and these methods allow you to sort lists efficiently based on various criteria.