What Is a Lambda?
A lambda is a way to create a small, single-line, anonymous function.
Regular function:
def double(x):
return x * 2
result = double(5) # 10
Lambda function:
double = lambda x: x * 2
result = double(5) # 10
Same function, but shorter! ⚡
Lambda Syntax
lambda arguments: expression
Parts:
- lambda — the keyword
- arguments — parameters (like in def)
- : — separator
- expression — what to return (ONE line only!)
Lambda Examples
1. Basic arithmetic
# Addition
add = lambda a, b: a + b
print(add(3, 5)) # 8
# Square of a number
square = lambda x: x ** 2
print(square(4)) # 16
# Even check
is_even = lambda n: n % 2 == 0
print(is_even(10)) # True
print(is_even(7)) # False
2. With strings
# Greeting
greet = lambda name: f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
# String length
length = lambda s: len(s)
print(length("Python")) # 6
3. With conditions
# Maximum of two
max_num = lambda a, b: a if a > b else b
print(max_num(10, 20)) # 20
# Positive or negative
sign = lambda x: "+" if x >= 0 else "-"
print(sign(5)) # +
print(sign(-3)) # -
When Should You Use Lambda?
✅ Good use cases:
1. Inside other functions:
numbers = [1, 2, 3, 4, 5]
# sorted with lambda
sorted_desc = sorted(numbers, key=lambda x: -x)
print(sorted_desc) # [5, 4, 3, 2, 1]
# map with lambda (coming soon!)
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # [2, 4, 6, 8, 10]
2. Simple transformations:
students = [
{"name": "Alice", "grade": 95},
{"name": "Bob", "grade": 87},
{"name": "Charlie", "grade": 92}
]
# Sort by grade
sorted_students = sorted(students, key=lambda s: s["grade"], reverse=True)
print(sorted_students[0]["name"]) # Alice
3. Generating data:
import random
# Lambda for random numbers
random_point = lambda: random.randint(0, 100)
points = [random_point() for _ in range(5)]
print(points) # [42, 17, 89, 5, 63] (random values!)
❌ Bad use cases:
1. Complex logic:
# ❌ BAD — too hard to read
check = lambda x: x > 0 and x < 100 and x % 2 == 0 and str(x)[0] != "5"
# ✅ GOOD — use a regular function
def check_number(x):
"""Check a number against criteria."""
if x <= 0 or x >= 100:
return False
if x % 2 != 0:
return False
if str(x)[0] == "5":
return False
return True
2. When you need a docstring:
# ❌ BAD — can't add a description
calculate = lambda x, y, z: (x + y) * z / 2
# ✅ GOOD — with documentation
def calculate_formula(x, y, z):
"""
Calculate using the formula: (x + y) * z / 2
Args:
x, y, z: Numbers for the calculation
Returns:
float: Result of the formula
"""
return (x + y) * z / 2
Lambda vs Regular Function
| Criterion | Lambda | def |
|---|---|---|
| Length | One line | Multiple lines OK |
| Name | Anonymous (no name) | Name required |
| Docstring | ❌ Not possible | ✅ Possible |
| Complexity | Simple operations | Any complexity |
| Usage | Inside other functions | Anywhere |
Practical Examples
Example 1: Sorting Products
products = [
{"name": "Laptop", "price": 50000},
{"name": "Mouse", "price": 500},
{"name": "Keyboard", "price": 3000}
]
# Sort by price
cheap_first = sorted(products, key=lambda p: p["price"])
expensive_first = sorted(products, key=lambda p: p["price"], reverse=True)
print(cheap_first[0]["name"]) # Mouse
print(expensive_first[0]["name"]) # Laptop
Example 2: Filtering Data
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Even only (using filter, coming soon!)
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even) # [2, 4, 6, 8, 10]
# Only > 5
big = list(filter(lambda x: x > 5, numbers))
print(big) # [6, 7, 8, 9, 10]
Example 3: Processing a List of Dictionaries
students = [
{"name": "Alice", "age": 20, "grade": 95},
{"name": "Bob", "age": 19, "grade": 87},
{"name": "Charlie", "age": 21, "grade": 92}
]
# Find the student with the highest grade
best = max(students, key=lambda s: s["grade"])
print(f"Best student: {best['name']} ({best['grade']})")
# Find the youngest
youngest = min(students, key=lambda s: s["age"])
print(f"Youngest: {youngest['name']} ({youngest['age']} years old)")
Multiple Parameters
A lambda can take multiple parameters:
# Two parameters
multiply = lambda x, y: x * y
print(multiply(5, 3)) # 15
# Three parameters
volume = lambda l, w, h: l * w * h
print(volume(2, 3, 4)) # 24
# Default values (won't work in lambda!)
# ❌ power = lambda x, n=2: x ** n # SyntaxError!
# Use def for default values:
def power(x, n=2):
return x ** n
Lambda with Built-In Functions
With sorted()
words = ["Python", "JavaScript", "Go", "C++", "Rust"]
# By word length
by_length = sorted(words, key=lambda w: len(w))
print(by_length) # ['Go', 'C++', 'Rust', 'Python', 'JavaScript']
# Reverse alphabetical order
reverse_alpha = sorted(words, key=lambda w: w.lower(), reverse=True)
print(reverse_alpha) # ['Rust', 'Python', 'JavaScript', 'Go', 'C++']
With max() and min()
data = [10, 3, 45, 7, 89, 12]
# Maximum element (no lambda needed here)
print(max(data)) # 89
# Maximum by absolute value
numbers = [-50, 10, -30, 5]
max_abs = max(numbers, key=lambda x: abs(x))
print(max_abs) # -50 (absolute value 50 is the largest!)
Common Mistakes
Mistake 1: Multiple lines
# ❌ ERROR — lambda can only be ONE line!
calc = lambda x:
result = x * 2
return result
# ✅ CORRECT
calc = lambda x: x * 2
Mistake 2: Assignments
# ❌ ERROR — you can't use assignment inside lambda
update = lambda x: x = x + 1 # SyntaxError!
# ✅ CORRECT — use a regular function
def update(x):
x = x + 1
return x
Mistake 3: Forgot return
# ❌ BAD
def double(x):
x * 2 # Forgot return!
result = double(5)
print(result) # None
# ✅ GOOD — lambda always returns
double = lambda x: x * 2
result = double(5)
print(result) # 10
When NOT to Use Lambda?
Don’t assign it to a variable!
# ❌ BAD PRACTICE
double = lambda x: x * 2
square = lambda x: x ** 2
add = lambda a, b: a + b
# ✅ GOOD — use def
def double(x):
return x * 2
def square(x):
return x ** 2
def add(a, b):
return a + b
Why?
- Lambda is for one-off use
- If you’re saving it to a variable → it needs a name → use def!
Summary
Lambda — what it is:
- ✅ An anonymous single-line function
- ✅ Convenient inside other functions
- ✅ Short and concise
- ❌ NOT for complex logic
- ❌ NOT for saving to named variables
Syntax:
lambda parameters: expression
Typical usage:
# Sorting
sorted(data, key=lambda x: x["field"])
# With map/filter (coming soon!)
list(map(lambda x: x * 2, numbers))
list(filter(lambda x: x > 0, numbers))
# Generation
[lambda_func() for _ in range(10)]
What’s Next?
Now you know lambda! 🎉
Next topics:
- map() — apply a function to each element of a list
- filter() — select elements by condition
- reduce() — fold a list into a single value
Lambda is the foundation of functional programming in Python! 🚀
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!