How to Sort Using Lambda in Python: Simple Guide
In Python, you can sort a list using the
sorted() function or the .sort() method with a key argument set to a lambda function. The lambda defines the sorting criteria by returning the value to sort by for each element.Syntax
The basic syntax to sort a list using a lambda function is:
sorted(iterable, key=lambda x: expression)- returns a new sorted list.list.sort(key=lambda x: expression)- sorts the list in place.
The lambda x: expression is an anonymous function that takes each element x and returns the value used for sorting.
python
sorted_list = sorted(my_list, key=lambda x: x[1]) my_list.sort(key=lambda x: x[1])
Example
This example shows how to sort a list of tuples by the second item using a lambda function.
python
data = [(1, 'banana'), (3, 'apple'), (2, 'cherry')] sorted_data = sorted(data, key=lambda x: x[1]) print(sorted_data)
Output
[(3, 'apple'), (1, 'banana'), (2, 'cherry')]
Common Pitfalls
Common mistakes include:
- Not using the
keyargument and expectinglambdato sort directly. - Modifying the list inside the lambda, which should only return a value.
- Confusing
sorted()(returns new list) with.sort()(modifies in place).
python
data = [3, 1, 2] # Wrong: lambda alone does not sort # sorted(data) # sorts by value, no lambda used # Right: use lambda with key sorted_data = sorted(data, key=lambda x: -x) # sorts descending print(sorted_data)
Output
[3, 2, 1]
Quick Reference
Summary tips for sorting with lambda:
- Use
key=lambda x: ...to specify sorting criteria. sorted()returns a new sorted list..sort()changes the original list.- Lambda should return the value to sort by, not modify data.
Key Takeaways
Use the key argument with a lambda function to define custom sorting criteria.
sorted() returns a new list, while list.sort() modifies the list in place.
Lambda functions should only return the sorting key, not change the data.
Remember to use key=lambda x: expression, not just lambda alone.
Sorting by complex criteria is easy by adjusting the lambda expression.