Sorting is a fundamental operation in programming, and Python provides the .sort() method to make it easy to sort lists in place. When combined with the key parameter and lambda functions, .sort() becomes a powerful tool for custom sorting. In this tutorial, we’ll explore the traditional approach to sorting, introduce the .sort() method with lambda, and provide examples to solidify your understanding.
What is .sort() with Lambda?
The .sort() method modifies a list in place, arranging its elements in a specified order (ascending by default). The key parameter allows you to define a custom sorting criterion, and a lambda function provides a concise way to specify that criterion without defining a separate function.
Syntax:
list.sort(key=lambda x: expression)
- .sort(): Sorts the list in place.
- key=: Specifies the sorting rule.
- lambda x: expression: An anonymous function where x is each list element, and expression defines what to sort by.
Examples of Sorting with .sort() and Lambda
Example 1: Sorting a List of Strings Alphabetically
Using a basic .sort():
fruits = ["banana", "apple", "cherry"]
fruits.sort() # Default alphabetical sort
print(fruits)
# Output: ['apple', 'banana', 'cherry']
Using .sort() with lambda:
fruits = ["banana", "apple", "cherry"]
fruits.sort(key=lambda x: x[0]) # Sort by the first character
print(fruits)
# Output: ['apple', 'banana', 'cherry']
In this case, sorting by the first character (x[0]) gives the same result as the default sort, but it demonstrates how lambda works.
Example 2: Sorting a List of Tuples by the Second Element
Using a for loop (traditional approach):
fruits = [("banana", 3), ("apple", 2), ("cherry", 5)]
sorted_fruits = sorted(fruits, key=lambda x: x[1]) # Note: sorted() creates a new list
print(sorted_fruits)
# Output: [('apple', 2), ('banana', 3), ('cherry', 5)]
Using .sort() with lambda:
fruits = [("banana", 3), ("apple", 2), ("cherry", 5)] fruits.sort(key=lambda x: x[1]) # Sort by the second element (number) print(fruits) # Output: [('apple', 2), ('banana', 3), ('cherry', 5)]
Here, .sort() modifies the original list, sorting by the second element of each tuple (x[1]).
Example 3: Sorting Strings by Length
Using a basic .sort():
words = ["cat", "elephant", "dog"]
words.sort() # Default alphabetical sort
print(words)
# Output: ['cat', 'dog', 'elephant']
Using .sort() with lambda:
words = ["cat", "elephant", "dog"]
words.sort(key=lambda x: len(x)) # Sort by string length
print(words)
# Output: ['cat', 'dog', 'elephant']
The lambda function len(x) sorts the list based on the length of each string.
Example 4: Sorting a List of Tuples by Multiple Criteria
Using .sort() with lambda:
items = [("apple", 2), ("banana", 1), ("apple", 1)]
items.sort(key=lambda x: (x[0], x[1])) # Sort by fruit name, then number
print(items)
# Output: [('apple', 1), ('apple', 2), ('banana', 1)]
Here, the lambda returns a tuple (x[0], x[1]), sorting first by the fruit name and then by the number when names are identical.
Example 5: Sorting in Descending Order
Using .sort() with lambda and reverse:
numbers = [3, 1, 4, 1, 5]
numbers.sort(key=lambda x: x, reverse=True) # Sort in descending order
print(numbers)
# Output: [5, 4, 3, 1, 1]
The reverse=True parameter flips the sort order, and the lambda x: x sorts based on the elements themselves.
When to Use .sort() with Lambda
Use .sort() with lambda when:
- You need to sort a list in place based on a custom criterion.
- You want concise, readable code for simple sorting logic.
- The list contains complex elements like tuples or objects.
Do not use .sort() with lambda when:
- You need a new sorted list without modifying the original (use sorted() instead).
- The sorting logic is too complex for a single lambda expression.