Python Functional Programming: Lambda, Map, Reduce and Filter
Python provides several useful functions that make it easier to work with collections of data. Four important concepts are lambda functions, map(), reduce(), and filter().
1. Lambda Function
A lambda function is a small anonymous function that can be written in a single line. It is useful when we need a simple function for a short operation.
Example:
square = lambda x: x * x
print(square(5))Output:
25Here, the lambda function takes 5 as input and returns its square.
Two variables of lambda Function:
The general syntax is:
lambda variable1, variable2: expression
multiply = lambda a, b: a * b
print(multiply(5, 4))Output:
20How to use lambda function using single if:
greatest = lambda x, y: x if x > y else y
print(greatest(10, 20))Output:
20How it works:
x, y→ two numbersx > y→ condition- If true → returns
x - Otherwise → returns
y
2. map()
The map() function applies a given function to every item in an iterable such as a list. It is useful when we want to perform the same operation on all elements.
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x * x, numbers))
print(squares)Output:
[1, 4, 9, 16, 25]Here, map() applies the lambda function to every number in the list.
3. reduce()
The reduce() function applies a function cumulatively to the items of an iterable and reduces them to a single value. It is available in the functools module.
Get Durga Vara Prasad’s stories in your inbox
Join Medium for free to get updates from this writer.
Example:
from functools import reducenumbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total)Output:
15Here, reduce() adds all the numbers and produces a single result, 15.
4. filter()
The filter() function is used to select elements from an iterable based on a condition. It keeps only the elements for which the condition is true.
Example:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)Output:
[2, 4, 6]Here, filter() selects only the even numbers from the list.
Conclusion
Lambda functions, map(), reduce(), and filter() are useful features in Python that make data processing simpler and more efficient. Lambda functions allow us to write small functions in a single line, while map() transforms data, reduce() combines values into a single result, and filter() selects values based on a condition. Understanding these concepts helps us write clean, concise, and readable Python programs.









