Lambda Functions and Map, Filter, Reduce

📘 Python 👁 78 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

Lambda Functions and Map, Filter, Reduce in Python

Python provides anonymous functions (lambda) and higher-order functions like map, filter, and reduce to write concise and functional-style code.


1. Lambda Functions

  • Anonymous functions created using the lambda keyword.

  • Can have any number of arguments but only one expression.

  • Useful for short, simple functions.

Syntax:

lambda arguments: expression

Examples:

# Basic lambda square = lambda x: x * x print(square(5)) # 25 # Lambda with multiple arguments add = lambda a, b: a + b print(add(3, 4)) # 7 # Using lambda directly print((lambda x, y: x * y)(2, 3)) # 6

2. Map Function

  • map(function, iterable) applies a function to every element of an iterable.

  • Returns a map object (can be converted to list, tuple, etc.).

Example with lambda:

numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x * x, numbers)) print(squared) # [1, 4, 9, 16, 25]

Example with a regular function:

def double(x): return x * 2 result = list(map(double, numbers)) print(result) # [2, 4, 6, 8, 10]

3. Filter Function

  • filter(function, iterable) selects elements where the function returns True.

  • Returns a filter object.

Example with lambda:

numbers = [1, 2, 3, 4, 5, 6] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # [2, 4, 6]

Example with a regular function:

def is_odd(x): return x % 2 != 0 odd_numbers = list(filter(is_odd, numbers)) print(odd_numbers) # [1, 3, 5]

4. Reduce Function

  • reduce(function, iterable) applies a function cumulatively to the items of an iterable.

  • Returns a single value.

  • Requires importing from functools.

Example with lambda:

from functools import reduce numbers = [1, 2, 3, 4, 5] sum_total = reduce(lambda a, b: a + b, numbers) print(sum_total) # 15 product = reduce(lambda a, b: a * b, numbers) print(product) # 120

Example with regular function:

def multiply(a, b): return a * b product = reduce(multiply, numbers) print(product) # 120

5. Key Points

  • Lambda functions are best for small, simple operations.

  • Map transforms each element of a sequence.

  • Filter selects elements based on a condition.

  • Reduce aggregates elements into a single result.

  • Combining these allows concise, functional-style programming in Python.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes