Introduction
The Python Lambda sorted() function can sort lists in descending or ascending order by default. This lets us create our own sorting orders when we use a lambda function to sort a list.
This article explains how to sort a list using Python’s sorted() function and how to use lambda expressions in Python. It includes examples to help you understand how these concepts work.
What is sorted() function in Python?
This sorted() function sorts a group of data like a list and gives back a new list that has been sorted. This function constructs a new list and sorts it.
Syntax:
list.sorted(iterable, key function, reverse)
What is Lambda in sorted Python?
Lambda functions are anonymous functions in Python that are defined using the lambda keyword. It is primarily used to define anonymous functions that can or cannot accept argument(s) and return the value of the data/expression.
What is key Lambda in Python?
Key is frequently used in functions that take a callable as a parameter, such as sorted() (often the key keyword parameter). You might also provide an existing function in place of lambda, provided it is a callable object.
Both list.sort() and sorted() have a key parameter to specify a function (or other callable) to be called on each list element prior to making comparisons.
What does sorted() use in Python?
The sorted() function takes a key parameter that specifies a function to generate a sorting key and a reverse parameter that accepts True or False. By default, sorted() function sorts numbers by value and text alphabetically.
How do I sort list using lambda in Python?
You can use the Python Lambda sorted() function to sort a list quickly. This function returns a new list with the entries arranged in ascending order, while the original list remains intact.
Advanced ways to sort with Lambda
The advanced ways to sort with Lambda in Python are the following:
- Sort a list of numerical string data
- Sort a list of tuples
- Sort a list containing another list
- Sort a list of dictionaries
Sort a list of numerical string data
A list of six elements has been defined in the script. The sorted() function is used to sort the list, with lambda as the key parameter. The sorted list is printed with space using the print() function.
list1 = ['64', '55', '2', '1', '21', '99']
new_list1 = sorted(list1, key=lambda x: int(x[0:]))
print("The new and sorted list:", *new_list1, sep=' ')
Output:
The new and sorted list: 1 2 21 55 64 99
If you want to know more about how to print a list in Python, check out our Python Print List with Advanced Examples.
Sort a list of tuples
The code demonstrates three ways of sorting. The first sorted() function sorts the list by each tuple’s first element. The second sorted() function sorts the list by each tuple’s second element. The third sorted() function sorts the list by the third element of each tuple.
tuple1 = [("Apple", 3, 'Python01'), ("Banana", 2, 'Python03'), ("Carrot", 1, 'Python02')]
new_tuple1 = sorted(tuple1, key=lambda x: x[0])
print("Sorted by the first element:",*new_tuple1)
new_tuple2 = sorted(tuple1, key=lambda x: x[1])
print("Sorted by the second element:",*new_tuple2)
new_tuple3 = sorted(tuple1, key=lambda x: x[2])
print("Sorted by the third element:",*new_tuple3)Output:
Sorted by the first element:, ('Apple', 3, 'Python01'), ('Banana', 2, 'Python03'), ('Carrot', 1, 'Python02')
Sorted by the second element:, ('Carrot', 1, 'Python02'), ('Banana', 2, 'Python03'), ('Apple', 3, 'Python01')
Sorted by the third element:, ('Apple', 3, 'Python01'), ('Carrot', 1, 'Python02'), ('Banana', 2, 'Python03')Sort a list containing another list
A blank list stores the values of the sorted list. The nested list is sorted by nested for loops. The outer for loop iterates based on the main list’s inner lists.
The inner for loop iterates each inner list. The lambda function in the inner loop calls sorted() to sort the nested list.
nested1 = [['Apple', 'Carrot', 'Banana'], ['Prince', 'Grace'], ['Dog', 'Cat', 'Bird', 'Ants']]
nested_data = []
for i in range(len(nested1)):
for j in range(len(nested1[i])):
new_nested1 = sorted(nested1[i], key=lambda x:x[0])
nested_data.append(new_nested1)
print("Nested List after Sorting: {}".format(nested_data))
Output:
Nested List after Sorting: [['Apple', 'Banana', 'Carrot'], ['Grace', 'Prince'], ['Ants', 'Bird', 'Cat', 'Dog']]Sort a list of dictionaries
Each dictionary in the list contains three key-value pairs. The code demonstrates four types of sorting: based on the code key, the name key, both code and name keys, and in descending order based on the name key.
dictionary1 = [{"subject": "English", "name": "Grammar", "Score": 99},
{"subject": "Science", "name": "Biology", "Score": 50},
{"subject": "Math", "name": "Calculus", "Score": 120}]
print("Sorting by code:\n", sorted(dictionary1, key=lambda i: i['subject']))
print("Sorting by name:\n", sorted(dictionary1, key=lambda i: (i['name'])))
print("Sorting by code and name:\n", sorted(dictionary1, key=lambda i: (i['subject'], i['name'])))
print("Sorting in descending order by name:\n", sorted(dictionary1, key=lambda i: i['name'], reverse=True))Output:
Sorting by code:
[{'subject': 'English', 'name': 'Grammar', 'Score': 99}, {'subject': 'Math', 'name': 'Calculus', 'Score': 120}, {'subject': 'Science', 'name': 'Biology', 'Score': 50}]
Sorting by name:
[{'subject': 'Science', 'name': 'Biology', 'Score': 50}, {'subject': 'Math', 'name': 'Calculus', 'Score': 120}, {'subject': 'English', 'name': 'Grammar', 'Score': 99}]
Sorting by code and name:
[{'subject': 'English', 'name': 'Grammar', 'Score': 99}, {'subject': 'Math', 'name': 'Calculus', 'Score': 120}, {'subject': 'Science', 'name': 'Biology', 'Score': 50}]
Sorting in descending order by name:
[{'subject': 'English', 'name': 'Grammar', 'Score': 99}, {'subject': 'Math', 'name': 'Calculus', 'Score': 120}, {'subject': 'Science', 'name': 'Biology', 'Score': 50}]Summary
This article provides examples of using lambda to sort four distinct lists. These examples should help Python users understand the purpose of Python lambda Sorted.
Related Python Tutorials
- Python Reduce Function With Example Program
- Python Lower Method With Advanced Examples
- Python Print List With Advanced Examples
- Python Set Union With Advanced Examples
- Python Constants With Advanced Examples
- Python Pi With Advanced Example
Common use cases for How Python Lambda Sorted with Advanced Examples
- Data pipelines. Python is the standard for ETL, data analysis, and ML workflows.
- Web development. Django and FastAPI power modern web backends and APIs.
- Automation and scripting. System administration, file processing, web scraping, and cron jobs.
- Machine learning. scikit-learn, PyTorch, TensorFlow, Hugging Face for AI/ML projects.
- Educational tools. Python’s readability makes it the go-to teaching language.
Working code example
from typing import Optional
def process_data(items: list[dict]) -> Optional[dict]:
"""Process a list of items and return summary stats."""
if not items:
return None
return {
"count": len(items),
"total": sum(item.get("value", 0) for item in items),
"avg": sum(item.get("value", 0) for item in items) / len(items),
}
# Usage
data = [{"value": 10}, {"value": 20}, {"value": 30}]
summary = process_data(data)
print(summary) # {'count': 3, 'total': 60, 'avg': 20.0}
Best practices
- Use type hints. list[dict], Optional[str], and TypedDict make code self-documenting and enable static analysis.
- Follow PEP 8. Consistent style improves readability. Use black or ruff to auto-format.
- Prefer f-strings. f”{value}” is cleaner than str.format() or % formatting.
- Write tests with pytest. Aim for 70%+ coverage on business-critical modules.
- Use ruff or pylint. Static analysis catches many bugs before code runs.
Common pitfalls
- Mutable default arguments. def f(x=[]) reuses the same list across calls. Use x=None then check.
- Integer division. 5/2 gives 2.5 in Python 3. Use // for floor division.
- Missing self on methods. Class methods need self as first parameter.
- Late binding closures. Loops that create lambdas can capture variables late.
