🕯️ Magic Note
The name “lambda” comes from lambda calculus, a mathematical system for expressing computation. Python borrowed the name but simplified the concept. In Python, a lambda is just a function you can write in one line. No complex theory required. Just convenience.
Python
# Basic lambda example
square = lambda x: x ** 2
print(square(5)) # 25
# Compare with regular function
def square_regular(x):
return x ** 2
# Both do the same thing. Lambda is shorter.
Python
# Lambda with two parameters
add = lambda a, b: a + b
print(add(3, 5)) # 8
# Lambda with three parameters
multiply_and_add = lambda x, y, z: x * y + z
print(multiply_and_add(2, 3, 4)) # (2 * 3) + 4 = 10
Python
# Lambda with default parameter
greet = lambda name, greeting=”Hello”: f”{greeting}, {name}!”
print(greet(“Ali”)) # Hello, Ali!
print(greet(“Sara”, “Hi”)) # Hi, Sara!
Python
# Lambda with ternary conditional
max_value = lambda a, b: a if a > b else b
print(max_value(10, 20)) # 20
absolute = lambda x: x if x >= 0 else -x
print(absolute(-5)) # 5
is_even = lambda x: True if x % 2 == 0 else False
# Or simpler:
is_even = lambda x: x % 2 == 0
print(is_even(4)) # True
Python
# Sorting a list of tuples by the second element
pairs = [(1, ‘one’), (3, ‘three’), (2, ‘two’), (4, ‘four’)]
pairs.sort(key=lambda x: x[1]) # Sort by the string (second element)
print(pairs) # [(4, ‘four’), (1, ‘one’), (3, ‘three’), (2, ‘two’)]
# Sorting strings by length
words = [“python”, “code”, “magic”, “conjure”]
words.sort(key=lambda w: len(w))
print(words) # [‘code’, ‘magic’, ‘python’, ‘conjure’]
# Finding the number with the largest absolute value
numbers = [-10, 5, -20, 15, -3]
largest_abs = max(numbers, key=lambda x: abs(x))
print(largest_abs) # -20
🕯️ Magic Note
Without lambdas, you would need to define a separate function for each simple key operation. Lambdas keep your code clean and local. The key function is right where it is used, not somewhere else in the file.
Python
# Using lambda with map()
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares) # [1, 4, 9, 16, 25]
# Using lambda with filter()
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4]
# Equivalent list comprehensions (often more readable)
squares = [x ** 2 for x in numbers]
evens = [x for x in numbers if x % 2 == 0]
Python
# List of dictionaries
users = [
{“name”: “Ali”, “age”: 25, “score”: 95},
{“name”: “Sara”, “age”: 30, “score”: 88},
{“name”: “Reza”, “age”: 22, “score”: 92},
{“name”: “Mina”, “age”: 28, “score”: 96}
]
# Sort by age
users.sort(key=lambda user: user[“age”])
print([u[“name”] for u in users]) # [‘Reza’, ‘Ali’, ‘Mina’, ‘Sara’]
# Sort by score (descending)
users.sort(key=lambda user: user[“score”], reverse=True)
print([u[“name”] for u in users]) # [‘Mina’, ‘Ali’, ‘Reza’, ‘Sara’]
# Sort by name length
users.sort(key=lambda user: len(user[“name”]))
print([u[“name”] for u in users]) # [‘Ali’, ‘Sara’, ‘Reza’, ‘Mina’]
- No statements allowed (no return, print as statement? print is a function, so it is allowed, but assignments are statements)
- No loops (for, while)
- No multiple expressions (only one)
- No annotations (type hints for lambda parameters are allowed in some Python versions, but syntax is awkward)
- No docstrings (cannot attach documentation)
Python
# This is NOT allowed in lambda:
# lambda x: return x*2 # return is a statement
# lambda x: x=5 # assignment is a statement
# lambda x: for i in range(x): print(i) # loops are statements
# This works because print is a function:
say = lambda x: print(f”Hello {x}”)
say(“Ali”) # Hello Ali
# But this defeats the purpose of lambda. Use def for side effects.
| Use Lambda When... | Use def When... |
|---|---|
| The operation is a single expression | The operation requires multiple lines or statements |
| You need a simple key function for sorting | You need complex logic or loops |
| You are passing a function to map/filter and the logic is short | You need a docstring or type hints |
| The function will be used only once (inline) | The function will be reused multiple times |
| You want to keep the code compact | Clarity is more important than brevity |
Python
# Good lambda usage (simple key function)
words.sort(key=lambda w: w[-1]) # Sort by last letter
# Bad lambda usage (too complex, should be def)
result = (lambda x: x * 2 if x > 0 else (x * -2 if x < -5 else x))(42)
# This is unreadable. Use a regular function instead.
Python
# Conceptual example (not runnable without GUI framework)
# button = Button(text=”Click me”, command=lambda: print(“Clicked!”))
# Passing arguments to callbacks
# buttons = []
# for i in range(5):
# btn = Button(text=f”Button {i}”, command=lambda i=i: print(f”Button {i} clicked”))
# buttons.append(btn)
# Note: The i=i captures the current value of i.
🕯️ Magic Note
The lambda i=i: … pattern is a common Python trick. It captures the current value of i in the lambda’s default parameter. Without it, the lambda would use the final value of i after the loop ends.
- Forgetting that lambda returns the expression (no return needed)
- Trying to put statements inside a lambda
- Overusing lambdas when a regular function would be clearer
- Using lambda when a list comprehension would be more readable
- Not capturing loop variables correctly (lambda: i vs lambda i=i: i)
- Assuming lambdas are faster than regular functions (they are not)
Python
# Common mistake: Loop variable capture in lambda
funcs = []
for i in range(3):
funcs.append(lambda: i) # All lambdas will return 2 (the last i)
print(funcs[0]()) # 2, not 0!
# Fix: Capture the current value
funcs = []
for i in range(3):
funcs.append(lambda i=i: i) # Each lambda captures its own i
print(funcs[0]()) # 0
print(funcs[1]()) # 1
- Write a lambda that returns the square of a number plus 5.
- How do you sort a list of strings by their length using a lambda?
- What is the main limitation of lambda functions?
- Write a lambda that takes two numbers and returns the larger one.
- When would you choose a regular def function over a lambda?
- What is the problem with lambda: i inside a loop and how do you fix it?
⚡ Whisper
A lambda is a tiny spell. One line. No name. No ceremony. You whisper it into existence, use it once, and let it fade. It is not for big magic. It is not for complex rituals. It is for the small moments. Sorting by the second element. Filtering with a simple condition. Mapping one value to another without declaring a full function. The lambda is humble. It does not seek attention. It does not demand a name. It just works, quickly and quietly. But be careful. A lambda forced to do too much becomes a curse. It stretches across multiple lines in your mind. It hides complex logic behind a tiny arrow. Know when to use a lambda and when to use def. The lambda is a scalpel, not a saw. Use it for precise cuts. For anything larger, reach for a proper function. Your code will thank you. And so will the programmers who read it later.