
Python
Lambda functions are small, unnamed functions you can write in one line. Perfect for quick operations.
A lambda is a small, unnamed function you can write in one line without using the `def` keyword. It's perfect for tiny operations where a full function definition would be overkill. Lambda functions are especially useful when you need a function just for one quick use, like inside a `map()` or `filter()` call.
# Regular function
def add(a, b):
return a + b
# Lambda function (same thing, one line)
add_lambda = lambda a, b: a + b
print(add(5, 3)) # Output: 8
print(add_lambda(5, 3)) # Output: 8# Square a number
square = lambda x: x ** 2
print(square(5)) # Output: 25
# Check if number is even
is_even = lambda x: x % 2 == 0
print(is_even(4)) # Output: True
print(is_even(7)) # Output: FalseThe `map()` function is perfect for transforming data. It takes a function and applies it to every item in a list, creating a new list with the transformed values. Lambda is ideal here because you can define your transformation inline without needing a separate function definition. It's a clean, readable way to modify all items in a collection at once.
numbers = [1, 2, 3, 4, 5]
# Double every number
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # [2, 4, 6, 8, 10]
# Square every number
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]The `filter()` function lets you select only the items from a list that meet a certain condition. Your lambda function returns `True` or `False` for each item, and `filter()` keeps only the items where it's `True`. This is a powerful way to clean, organize, or extract specific data from a collection without writing a loop manually.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Keep only even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]
# Keep only numbers > 5
big = list(filter(lambda x: x > 5, numbers))
print(big) # [6, 7, 8, 9, 10]Use lambda when:
Don't use lambda when:
| Concept | Remember |
|---|---|
| Lambda | Quick one-line function |
| Syntax | `lambda arguments: return_value` |
| Use case | Simple operations with map/filter |
| When not to | Complex functions → use def |
Now let's explore decorators — functions that enhance other functions!
Ready to practice? Try challenges or view solutions
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward