🕯️ Magic Note
A lambda function can take any number of arguments but can only contain a single expression. That expression is evaluated and returned automatically. There is no return statement. The result of the expression is the return value.
- Can take multiple arguments: lambda x, y: x + y
- Can take zero arguments: lambda: “Hello”
- Can have default values: lambda x, y=10: x + y
- Cannot contain statements or multiple lines
| Lambda | Equivalent def | Usage |
|---|---|---|
| lambda x: x*2 | def f(x): return x*2 | Double a number |
| lambda x, y: x > y | def f(x,y): return x>y | Compare two values |
| lambda s: s.lower() | def f(s): return s.lower() | Convert to lowercase |
| lambda: random.random() | def f(): return random.random() | Generate random number |
Python
# Using lambda with sorted
words = [“python”, “magic”, “code”, “whisper”]
sorted_words = sorted(words, key=lambda w: len(w))
print(sorted_words)
# Output: [“code”, “magic”, “python”, “whisper”]
# Sorted by word length
Python
# Using lambda with filter
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
# Output: [2, 4, 6, 8]
Python
# Using lambda with map
temps_celsius = [0, 10, 20, 30, 40]
temps_fahrenheit = list(map(lambda c: (c * 9/5) + 32, temps_celsius))
print(temps_fahrenheit)
# Output: [32.0, 50.0, 68.0, 86.0, 104.0]
- Trying to put multiple expressions or statements inside a lambda, you can only have one expression
- Forgetting to call the lambda, writing lambda x: x*2 instead of (lambda x: x*2)(5) or assigning it to a variable
- Using lambda when a simple expression or list comprehension would be cleaner and more readable
⚡ Whisper
A name is a heavy cloak. Some spells work best in silence. Appear. Transform. Vanish. The lambda leaves no trace but the result of its work.