Gyaan

Lambda Functions

beginner lambda anonymous-functions functional

A lambda is a small anonymous function — a function without a name. It can take any number of arguments but can only have a single expression. Think of it as a shortcut for tiny throwaway functions.

Basic Syntax

# Regular function
def double(x):
    return x * 2

# Lambda equivalent
double = lambda x: x * 2

double(5)  # 10

Notice there’s no return keyword. The expression after the colon is automatically returned.

Where Lambdas Actually Shine

We rarely assign lambdas to variables (that defeats the purpose — just use def). Their real power is as inline arguments to functions like sorted(), map(), and filter().

Sorting with a Custom Key

users = [
    {"name": "Charlie", "age": 30},
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 28},
]

# Sort by age
sorted_users = sorted(users, key=lambda u: u["age"])
# [Alice(25), Bob(28), Charlie(30)]

# Sort by name length
sorted_users = sorted(users, key=lambda u: len(u["name"]))

With map() and filter()

nums = [1, 2, 3, 4, 5]

# Double each number
doubled = list(map(lambda x: x * 2, nums))
# [2, 4, 6, 8, 10]

# Keep only even numbers
evens = list(filter(lambda x: x % 2 == 0, nums))
# [2, 4]

Multiple Arguments

Lambdas can take multiple arguments, separated by commas.

add = lambda a, b: a + b
add(3, 4)  # 7

# Sorting tuples by second element
pairs = [(1, 'b'), (3, 'a'), (2, 'c')]
sorted(pairs, key=lambda p: p[1])
# [(3, 'a'), (1, 'b'), (2, 'c')]

Limitations

Lambdas can only contain a single expression. No statements, no assignments, no multi-line logic.

# This is NOT allowed
bad = lambda x: if x > 0: return x  # SyntaxError

# This IS allowed (conditional expression)
absolute = lambda x: x if x >= 0 else -x

Lambda vs def — When to Use Which

  • Use lambda when we need a short, one-off function as an argument (like a sort key)
  • Use def for everything else — named functions, multi-line logic, functions we’ll reuse
# Good use of lambda — short, inline, throwaway
sorted(items, key=lambda x: x.priority)

# Bad use of lambda — just use def
process = lambda x, y: x ** 2 + y ** 2 - 2 * x * y  # hard to read

Common Interview Pattern

We might be asked to sort a list of strings by their last character.

words = ["banana", "apple", "cherry"]
sorted(words, key=lambda w: w[-1])
# ['banana', 'apple', 'cherry'] → sorted by 'a', 'e', 'y'

In simple language, lambdas are one-line functions we write when creating a full def feels like overkill. The only difference is they can only do one thing — one expression, no more.