0%

33- Lambda (Anonymous) Functions

Small, one-line functions without a name. Perfect for short operations where a full function definition is overkill. Lambda is your lightweight spell.

Sometimes you need a function for a simple task. A function that takes one argument and returns its square. A function that checks if a number is even. A function that maps a value to another value. Writing a full def function for these tiny operations feels heavy. You need a name. You need a dedicated line for def. You need an indented body. Then you probably use it only once. Lambda functions are the solution. They are anonymous functions defined in a single line. No name required (though you can assign them to variables). No def keyword. No return statement (the expression is automatically returned). Just a compact, inline function. Lambda functions are not more powerful than regular functions. They are just more convenient for small, simple operations.

🕯️ 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.

Lambda Syntax
The syntax is: lambda parameters: expression – The keyword lambda comes first – Then the parameters (comma-separated, no parentheses needed) – Then a colon – Then the expression (what to return) The expression is evaluated and returned automatically. No explicit return needed.

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.

💡 Lambda functions are often used without assigning them to variables. You define and use them in the same line, like result = (lambda x: x*2)(5). But this hurts readability. Assigning a lambda to a variable defeats its purpose. Use them inline or use def.
Lambda with Multiple Parameters
Lambdas can take multiple parameters, just like regular functions.

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

Lambda with Default Parameters
Lambdas support default parameters, just like regular functions.

Python

# Lambda with default parameter

greet = lambda name, greeting=”Hello”: f”{greeting}, {name}!”

print(greet(“Ali”)) # Hello, Ali!

print(greet(“Sara”, “Hi”)) # Hi, Sara!

⚠️ Lambdas cannot contain statements. Only a single expression. This means no print() inside (it is a statement, not an expression? Actually print is a function now, but assignments are statements). You cannot use return, if-else (but you can use ternary conditional), loops, or multiple lines.
Lambda with Conditional (Ternary) Expression
You can use the ternary conditional operator inside a lambda since it is an expression, not a statement.

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

Primary Use Case: key Functions
The most common place to see lambdas is as key functions in sorted(), min(), max(), and list.sort().

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.

Secondary Use Case: map() and filter()
Lambdas work perfectly with map() and filter(). But note: list comprehensions are often more readable.

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]

💡 Many Python programmers prefer list comprehensions over map() and filter() with lambdas. Comprehensions are usually more readable. Use lambdas with these functions only when the operation is very simple or when you need lazy evaluation with large data.
Tertiary Use Case: sort() with Complex Keys
Lambdas become essential when sorting a list of dictionaries or objects by a specific field.

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’]

Limitations of Lambdas
Lambdas are limited by design. They cannot contain statements. They cannot do everything a regular function can.
  • 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.

Lambda vs Regular Function: When to Use Which
Use Lambda When...Use def When...
The operation is a single expressionThe operation requires multiple lines or statements
You need a simple key function for sortingYou need complex logic or loops
You are passing a function to map/filter and the logic is shortYou 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 compactClarity 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.

Lambda in Event Handlers and GUI Programming
Lambdas are useful for simple callbacks in GUI and event-driven programming.

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.

Common Mistakes with Lambdas
  • 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

Check Your Understanding
  • 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.

Related posts