← Back to Python

All Topics

Advertisement

Learn/Python/Advanced Python

Map, Filter, Reduce

Topic: Functional Programming

Advertisement

Introduction

Map, filter, and reduce are fundamental functional programming constructs.

Map

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

# Multiple iterables
a = [1, 2, 3]
b = [4, 5, 6]
added = list(map(lambda x, y: x + y, a, b))
print(added)  # [5, 7, 9]

Filter

# Keep elements matching condition
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4, 6, 8, 10]

# With None to filter truthy values
falsy = [0, 1, "", "hello", None, [], True]
truthy = list(filter(None, falsy))
print(truthy)  # [1, 'hello', True]

Reduce

from functools import reduce

# Accumulate to single value
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers, 1)  # 120

# With initial value
max_val = reduce(lambda a, b: a if a > b else b, [3, 1, 4, 1, 5])

Practice Problems

  1. Apply multiple transformations with map
  2. Filter even numbers and square them
  3. Find maximum using reduce
  4. Compose map and filter operations
  5. Use reduce to build dictionaries

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →