The Python sort() method is a powerful and convenient way to arrange lists in ascending or descending order. Whether you're working with numbers, strings, or custom objects, mastering sort() will make your Python code more efficient and organized.
Basic Syntax
The sort() method is called on a list and modifies the list in place:
list.sort(key=None, reverse=False)
- key (optional): A function that serves as a basis for sorting. Defaults to `None`.
-reverse (optional): A boolean that determines the sorting order. Set to `True` for descending order. Defaults to `False`.
Common Examples
1. Sorting a List of Numbers
By default, sort() arranges numbers in ascending order:
numbers = [4, 2, 9, 1]
numbers.sort()
print(numbers)
Output:
[1, 2, 4, 9]
2. Sorting in Descending Order
Use the reverse=True argument for descending order:
numbers.sort(reverse=True)
print(numbers)
Output:
[9, 4, 2, 1]
3. Sorting Strings
Strings are sorted alphabetically by default:
fruits = ["banana", "apple", "cherry"]
fruits.sort()
print(fruits)
Output:
['apple', 'banana', 'cherry']
4. Sorting with a Key Function
The key parameter allows custom sorting logic. For example, sort by string length:
fruits.sort(key=len)
print(fruits)
Output:
['apple', 'banana', 'cherry']
You can also use lambda functions for more advanced criteria:
fruits.sort(key=lambda x: x[-1]) # Sort by the last character
print(fruits)
Output:
['banana', 'apple', 'cherry']
Differences Between sort() and sorted()
You might encounter various use cases for sorting in Python, and these may be using the sort() or sorted() methods. But what's the difference?
- sort(): Modifies the list in place and returns None.
- sorted(): Returns a new sorted list, leaving the original list unchanged.
Example:
numbers = [4, 2, 9, 1]
sorted_numbers = sorted(numbers)
print(numbers) # Original list remains unchanged
print(sorted_numbers) # New sorted list
Output:
[4, 2, 9, 1]
[1, 2, 4, 9]
Common Use Cases
1. Sorting Complex Objects
When working with dictionaries or custom objects, the `key` parameter can specify the sorting criteria:
students = [{"name": "Alice", "grade": 85}, {"name": "Bob", "grade": 92}]
students.sort(key=lambda x: x['grade'])
print(students)
Output:
[{'name': 'Alice', 'grade': 85}, {'name': 'Bob', 'grade': 92}]
2. Case-Insensitive Sorting
Sort strings without considering case:
fruits = ["Banana", "apple", "Cherry"]
fruits.sort(key=str.lower)
print(fruits)
Output:
['apple', 'Banana', 'Cherry']
Key Takeaways
- The sort() method is ideal for in-place sorting of lists.
- Use the key parameter for custom sorting logic.
- Use reverse=True for descending order.
- Opt for sorted() if you need to keep the original list unchanged in your Python projects.
Practice Exercise
Here's a simple challenge you can attempt, try sorting the following list of tuples by the second element in descending order:
data = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
data.sort(key=lambda x: x[1], reverse=True)
print(data)
Wrapping Up
Python's sort() method is a versatile and efficient way to organize your data. With options like the key parameter and reverse sorting, you can customize your sorting logic for any scenario. Happy coding!