Monday, August 25, 2025

๐ŸMAP, FILTER AND REDUCE

Python provides powerful built-in functions like map(), filter(), and reduce() to work with data more efficiently. They are especially useful with lambda functions.

1) Introduction

These functions belong to the concept of functional programming. - map() → Applies a function to every element of an iterable. - filter() → Selects elements based on a condition. - reduce() → Reduces a sequence to a single value by applying a function cumulatively.

2) The map() Function


# Syntax
map(function, iterable)

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

Use case: Transforming data without writing explicit loops.

3) The filter() Function


# Syntax
filter(function, iterable)

# Example: Filter even numbers
nums = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)  # [2, 4]

Use case: Extracting only elements that satisfy a condition.

4) The reduce() Function

reduce() is not a built-in like map() and filter(). It is available in the functools module.


from functools import reduce

# Syntax
reduce(function, iterable)

# Example: Multiply all numbers
nums = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, nums)
print(product)  # 120

Use case: Cumulative computations like sum, product, max, etc.

5) Comparison with Loops

Everything done with map(), filter(), and reduce() can also be achieved with for loops. However, these functions make the code more concise and functional.


# Using a for loop
nums = [1, 2, 3, 4, 5]
doubled = []
for n in nums:
    doubled.append(n * 2)

print(doubled)  # [2, 4, 6, 8, 10]

6) Common Mistakes

  • Forgetting to wrap results with list() in Python 3 (map/filter return iterators).
  • Using reduce() without importing it from functools.
  • Writing overly complex lambdas — better to use def for clarity.

๐Ÿ’ก Try It Yourself

  1. Use map() to convert a list of strings to uppercase.
  2. Use filter() to extract numbers divisible by 3 from a list.
  3. Use reduce() to find the maximum number in a list.

๐Ÿ–ฅ️ Practice in Browser

No comments:

Post a Comment

๐ŸWhat is scikitlearn??