Home → Advanced → Lambda
Reading
0%

1 · Lambda Functions

In computer science, a lambda abstraction is the definition of an anonymous function. In Python, the lambda keyword creates a function object that can be used anywhere a function is expected, but without a formal name (unless assigned to a variable).

📖
Textbook Definition

"A lambda is an expression that creates a function object, but it is limited to a single expression. It is often called an 'anonymous function' because it doesn't require a def statement or a name." — Learning Python, Mark Lutz

Python
# Anonymous function to square a number
square = lambda x: x ** 2
print(square(5))  # Output: 25

# Immediately Invoked Function Expression (IIFE)
print((lambda x, y: x + y)(10, 20))  # Output: 30
🔁 Return Value

A lambda expression returns a function object at runtime. This object behaves exactly like a function defined with def, but it is restricted to a single expression whose result is the function's return value.

2 · map(): Functional Transformation

The map(function, iterable) function applies a given function to every item of an iterable (list, tuple, etc.) and returns a map object.

💡
FastAPI Style Tip

In modern Python, list comprehensions are often preferred over map() for readability, but map() is highly efficient when using built-in functions.

Python
names = ["alice", "bob", "charlie"]
upper_names = map(str.upper, names)
print(list(upper_names))  # ['ALICE', 'BOB', 'CHARLIE']
🔁 Return Value

In Python 3.x, map() returns an iterator (specifically a map object). It is lazy, meaning it doesn't compute the values until you iterate over it (e.g., using list() or a for loop).

3 · filter(): Boolean Selection

filter(function, iterable) constructs an iterator from those elements of an iterable for which the function returns true.

Python
numbers = [1, 2, 3, 4, 5, 6]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens))  # [2, 4, 6]
🔁 Return Value

Similar to map(), filter() returns a filter object (an iterator). Elements are processed only when requested, saving memory for large datasets.

📚 See Also