Python Lambda Functions
Table of Contents
In the last lesson, we learned about Python Variable-Length Arguments. Now let’s create a small function in one expression without writing a full def block.
Let’s Talk About Small Functions
We already know how to define functions using def.
def add(a, b): return a + bThat is fine. But sometimes we need a really small function. One that does one tiny thing. And we need it only once. Maybe we are passing it to another function. Or using it for a quick calculation.
Writing a full def block for that feels like too much work. Like using a whole paragraph to say one word.
That is where lambda functions come in.
What Is a Lambda Function in Python?
A lambda function is a small, anonymous function. Anonymous means it does not have a name.
It is a way to write a function in one line. Without the def keyword. Without a name.
Think of it like a sticky note. A regular function is like a full page in a notebook. A lambda is a quick note we write and stick somewhere. It does the job. But it is not meant to last.
The Structure of a Lambda Function
lambda parameters: expressionlambda— the keywordparameters— the inputs, just like a regular function:— colonexpression— a single expression that gets evaluated and returned
There is no return keyword. The expression itself is the return value.
Let me show us.
add = lambda a, b: a + bprint(add(5, 3))Output
8Here, add is a variable that holds the lambda function. We call it like a regular function.
But notice — we did not use def. We did not give the function a name in the usual way. We just wrote lambda a, b: a + b. That is the whole function.
Lambda vs Regular Function in Python
Let’s compare.
Regular function:
def add(a, b): return a + bLambda:
add = lambda a, b: a + bBoth do the same thing. Both can be called the same way.
But the lambda is shorter. It fits in one line. And it does not need a name.
However, lambda has limits. It can only contain a single expression. It cannot have multiple statements. No loops. No if blocks. No assignments. Just one expression.
So for simple things, lambda is great. For anything complex, use def.
Why Use Lambda in Python?
The main use of lambda is when we need a small function for a short time. Usually, we pass it to another function.
For example, the sorted() function can take a key argument. That key is a function that tells Python how to sort.
Let’s say we have a list of tuples. Each tuple has a name and age.
people = [("Alex", 25), ("Sam", 30), ("John", 22)]If we sort normally, it sorts by the first item (name).
print(sorted(people))Output
[('Alex', 25), ('John', 22), ('Sam', 30)]But what if we want to sort by age? We need to tell Python to use the second item.
print(sorted(people, key=lambda person: person[1]))Output
[('John', 22), ('Alex', 25), ('Sam', 30)]The key=lambda person: person[1] tells Python: for each person, use the item at index 1 (the age) to sort.
That is a perfect use of lambda. We need a small function just for this one sorting operation. We do not want to write a full def for it.
Lambda with filter() in Python
The filter() function takes a function and a list. It keeps only the items where the function returns True.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]evens = list(filter(lambda x: x % 2 == 0, numbers))print(evens)Output
[2, 4, 6, 8, 10]The lambda lambda x: x % 2 == 0 checks if a number is even. The filter keeps only the even numbers.
Lambda with map() in Python
The map() function applies a function to every item in a list.
numbers = [1, 2, 3, 4, 5]squares = list(map(lambda x: x ** 2, numbers))print(squares)Output
[1, 4, 9, 16, 25]The lambda squares each number. And map applies it to every item.
Lambda with No Arguments
We can have a lambda with no arguments.
greet = lambda: "Hello"print(greet())Output
HelloBut this is not very useful. Usually, lambdas take at least one argument.
Lambda with Multiple Arguments
We can have multiple arguments.
multiply = lambda a, b, c: a * b * cprint(multiply(2, 3, 4))Output
24That works. But if we have too many arguments, it becomes hard to read. Let’s use a regular function instead.
Lambda with Conditional Expression in Python
We can use a conditional expression inside a lambda.
max_value = lambda a, b: a if a > b else bprint(max_value(10, 20))Output
20The expression a if a > b else b returns the larger of the two. That is allowed because it is a single expression.
But we cannot use an if statement with multiple lines. Only the ternary expression.
When to Use Lambda in Python
Use lambda when:
- The function is very simple
- We need it only once
- We are passing it to another function like
sorted,filter, ormap - Writing a full
defwould be overkill
Do not use lambda when:
- The logic is complex
- We need multiple statements
- We need loops or conditions
- The lambda becomes hard to read
Readable code is always more important than short code.
Python Lambda Functions: A Real-Life Example
Let’s sort a list of dictionaries by a specific key.
products = [ {"name": "Laptop", "price": 1200}, {"name": "Phone", "price": 800}, {"name": "Tablet", "price": 500}]
sorted_products = sorted(products, key=lambda p: p["price"])for product in sorted_products: print(f"{product['name']}: ${product['price']}")Output
Tablet: $500Phone: $800Laptop: $1200That is clean. The lambda tells Python to sort by the “price” key.
Common Mistakes with Python Lambda Functions
Mistake 1: Trying to Use Statements in Lambda
f = lambda x: print(x); return x # Error!Lambda can only have one expression. No statements. No multiple lines.
Mistake 2: Assigning Lambda to a Variable and Using It Like a Regular Function
We can do it. But it is not recommended. If we need a named function, use def.
add = lambda a, b: a + b # Works, but not PythonicBetter:
def add(a, b): return a + bThe only reason to assign a lambda to a variable is if we really need a one-liner. Otherwise, use def.
Mistake 3: Forgetting That Lambda Returns the Expression
f = lambda x: x + 1This returns x + 1. There is no need for return. The expression is automatically returned.
Mistake 4: Using Lambda When a Regular Function Is Clearer
result = (lambda x, y: x * y + 10)(5, 3)This is confusing. Just write:
def calculate(x, y): return x * y + 10
result = calculate(5, 3)Much better.
Next, we will learn about Python Variable Scope and understand where each variable can be used.