0
0
Pythonprogramming~5 mins

Lambda with sorted() in Python

Choose your learning style9 modes available
Introduction
You use lambda with sorted() to quickly tell Python how to sort things without writing a full function.
When you want to sort a list of words by their length.
When you have a list of dictionaries and want to sort by a specific key.
When you want to sort numbers based on a custom rule, like sorting by the last digit.
When you need a quick way to sort without creating a separate function.
Syntax
Python
sorted(iterable, key=lambda item: expression)
The lambda function tells sorted() how to compare each item.
The 'key' argument is where you put the lambda to customize sorting.
Examples
Sorts numbers normally from smallest to largest.
Python
sorted([5, 2, 9, 1], key=lambda x: x)
Sorts words by their length.
Python
sorted(['apple', 'banana', 'pear'], key=lambda x: len(x))
Sorts a list of dictionaries by the 'age' key.
Python
sorted([{'name': 'Bob', 'age': 25}, {'name': 'Ann', 'age': 20}], key=lambda x: x['age'])
Sample Program
This program sorts the list of fruits by their length using a lambda function.
Python
fruits = ['apple', 'banana', 'pear', 'kiwi']
sorted_fruits = sorted(fruits, key=lambda x: len(x))
print(sorted_fruits)
OutputSuccess
Important Notes
Lambda functions are small, unnamed functions used for simple tasks.
Using lambda with sorted() is a quick way to customize sorting without extra code.
Summary
Use lambda with sorted() to sort items by any rule you want.
The lambda goes inside the 'key' argument to tell sorted() how to compare items.
This method keeps your code short and easy to read.