Lambda Functions
Learn what lambda functions are, how they work, and when to use them in Python.
Lambda Functions
A lambda function is a small, anonymous function written in one line. Anonymous means it has no name — you just define it and use it right away.
Before learning lambda, look at a normal function:
def double(x):
return x * 2
print(double(5)) # 10The exact same thing as a lambda:
double = lambda x: x * 2
print(double(5)) # 10Both do the identical thing. The lambda version is just shorter.
The syntax
lambda parameters: expressionlambda— the keyword that starts itparameters— the input, just like function parametersexpression— one single operation, its result is automatically returned
# normal function
def add(a, b):
return a + b
# same thing as lambda
add = lambda a, b: a + b
print(add(3, 4)) # 7A lambda can only have one expression. No multiple lines, no if/else blocks, no loops. It is designed for simple, short operations only. If your logic is more complex than one line — write a normal function.
Lambda with no arguments
greet = lambda: "Hello, world!"
print(greet()) # Hello, world!Lambda with one argument
square = lambda x: x ** 2
print(square(4)) # 16
print(square(10)) # 100Lambda with multiple arguments
multiply = lambda a, b: a * b
print(multiply(3, 5)) # 15
print(multiply(10, 2)) # 20Where lambda actually shines
Storing a lambda in a variable like double = lambda x: x * 2 is valid — but it is not the real reason lambdas exist. If you are doing that, just write a normal function.
Lambda's real power is when you need a short, throwaway function in one specific place — especially as an argument to another function.
sorted() — sorting with a custom rule
sorted() can sort a list by any rule you give it. You pass that rule using the key argument.
Say you have a list of names and you want to sort them by their length:
names = ["Ali", "Muhammad", "Sara", "Zainab", "Omar"]
sorted_names = sorted(names, key=lambda name: len(name))
print(sorted_names)
# ['Ali', 'Sara', 'Omar', 'Zainab', 'Muhammad']The lambda says — for each name, use its length as the sorting key. Shortest first.
Now sort a list of products by price:
products = [
{"name": "Phone", "price": 999},
{"name": "Earbuds", "price": 49},
{"name": "Laptop", "price": 1499},
{"name": "Mouse", "price": 29},
]
sorted_products = sorted(products, key=lambda p: p["price"])
for product in sorted_products:
print(f"{product['name']}: ${product['price']}")Output:
Mouse: $29
Earbuds: $49
Phone: $999
Laptop: $1499The lambda says — for each product dictionary, use the price value as the sorting key.
Sort by price in reverse (most expensive first):
sorted_products = sorted(products, key=lambda p: p["price"], reverse=True)map() — apply a function to every item
map() takes a function and a list, applies the function to every item, and gives back the results.
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]Without lambda you would need a whole separate function just for this:
def square(x):
return x ** 2
squared = list(map(square, numbers))Lambda saves you from naming and defining a function you will only use once.
Another example — convert a list of prices to include tax:
prices = [100, 250, 399, 50]
with_tax = list(map(lambda price: round(price * 1.15, 2), prices))
print(with_tax) # [115.0, 287.5, 458.85, 57.5]filter() — keep only items that pass a test
filter() takes a function and a list, runs the function on every item, and keeps only the items where the function returned True.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]The lambda says — keep this item only if it is even.
Filter a list of students who passed:
students = [
{"name": "Ali", "score": 88},
{"name": "Sara", "score": 45},
{"name": "Omar", "score": 72},
{"name": "Fatima", "score": 38},
{"name": "Zainab", "score": 91},
]
passed = list(filter(lambda s: s["score"] >= 50, students))
for student in passed:
print(f"{student['name']}: {student['score']}")Output:
Ali: 88
Omar: 72
Zainab: 91Lambda vs normal function — when to use which
| Situation | Use |
|---|---|
| Simple one-line operation passed to another function | Lambda |
| Logic needs more than one line | Normal function |
| You need to reuse the function in multiple places | Normal function |
| You need a docstring or clear name | Normal function |
| Sorting, filtering, mapping with a quick rule | Lambda |
A good rule — if your lambda is getting long or hard to read, it is telling you to write a normal function instead. Lambda is for short, obvious operations. Readability always wins.
A real example putting it together
You have a list of orders. Sort them by total price, then filter out only the ones that are delivered:
orders = [
{"id": 1, "status": "delivered", "total": 250},
{"id": 2, "status": "pending", "total": 89},
{"id": 3, "status": "delivered", "total": 540},
{"id": 4, "status": "cancelled", "total": 120},
{"id": 5, "status": "delivered", "total": 75},
]
delivered = filter(lambda o: o["status"] == "delivered", orders)
sorted_orders = sorted(delivered, key=lambda o: o["total"], reverse=True)
for order in sorted_orders:
print(f"Order #{order['id']} — ${order['total']}")Output:
Order #3 — $540
Order #1 — $250
Order #5 — $75Summary
| Concept | Example |
|---|---|
| Basic lambda | lambda x: x * 2 |
| Multiple arguments | lambda a, b: a + b |
| Sort by custom rule | sorted(list, key=lambda x: x["price"]) |
| Apply to every item | map(lambda x: x ** 2, list) |
| Filter items | filter(lambda x: x > 0, list) |