Functional Programming in Python (map, filter, reduce, lambda)

Functional Programming in Python (map, filter, reduce, lambda)

Functional programming is a programming paradigm that emphasizes the use of pure functions and avoids mutable state. Python provides some built-in functions to support a functional programming style, including map, filter, reduce, and lambda expressions. Below, I will explain the usage and applicable scenarios of these tools step by step.

1. Lambda Expressions

Description:
lambda is used to create anonymous functions (i.e., small functions without a name). It is suitable for simple operations and is often passed as an argument to higher-order functions (such as map, filter).

Syntax:
lambda parameters: expression

Example:

# Normal function definition
def add(x, y):
    return x + y

# Equivalent lambda expression
add_lambda = lambda x, y: x + y

print(add(2, 3))        # Output: 5
print(add_lambda(2, 3)) # Output: 5

Characteristics:

  • Can only contain a single expression; cannot include complex logic or statements (for if-else branches, use ternary expressions).
  • Automatically returns the result of the expression; no return keyword is needed.

2. The map Function

Description:
map applies a function to each element of one or more iterables (such as lists) and returns an iterator (in Python 3, use list() to convert to a list).

Syntax:
map(function, iterable1, iterable2, ...)

Example:

# Square each element in a list
numbers = [1, 2, 3, 4]
squared = map(lambda x: x**2, numbers)
print(list(squared))  # Output: [1, 4, 9, 16]

# Add corresponding elements from multiple iterables
list1 = [1, 2, 3]
list2 = [10, 20, 30]
result = map(lambda x, y: x + y, list1, list2)
print(list(result))   # Output: [11, 22, 33]

Note:

  • If the iterables are of different lengths, map stops at the shortest one.

3. The filter Function

Description:
filter selects elements from an iterable based on a function's condition, returning an iterator containing the elements for which the function returns True.

Syntax:
filter(function, iterable)

Example:

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

# Filter non-empty strings
words = ["hello", "", "world", None, " "]
non_empty = filter(lambda s: s and s.strip(), words)
print(list(non_empty))  # Output: ['hello', 'world']

Note:

  • If function is None, it directly filters elements that evaluate to True in the iterable.

4. The reduce Function

Description:
reduce performs a cumulative operation on the elements of an iterable (from left to right), ultimately reducing the sequence to a single value. Must be imported from the functools module.

Syntax:
reduce(function, iterable[, initializer])

Example:

from functools import reduce

# Calculate the product of list elements
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # Output: 24

# Calculate factorial (initial value set to 1)
factorial = reduce(lambda x, y: x * y, range(1, 6), 1)
print(factorial)  # Output: 120

Execution Process (using reduce(lambda x, y: x+y, [1, 2, 3, 4]) as an example):

  1. First step: calculate 1+2=3
  2. Second step: calculate 3+3=6
  3. Third step: calculate 6+4=10
    Final result is 10.

5. Integrated Application and Comparison

Scenario: Process the list [1, 2, 3, 4, 5], with requirements:

  • Filter even numbers → square them → sum them.

Step-by-step Implementation:

from functools import reduce

numbers = [1, 2, 3, 4, 5]
# 1. Filter even numbers
evens = filter(lambda x: x % 2 == 0, numbers)
# 2. Square them
squared = map(lambda x: x**2, evens)
# 3. Sum them
result = reduce(lambda x, y: x + y, squared)
print(result)  # Output: 2² + 4² = 4 + 16 = 20

Alternative (List Comprehension):

result = sum(x**2 for x in numbers if x % 2 == 0)

List comprehensions are often more concise, but the functional style can be clearer for complex pipeline operations.


6. Summary

  • lambda: Quickly define simple functions, avoiding code redundancy.
  • map: Apply a function to each element, generating a new sequence.
  • filter: Filter elements based on a condition.
  • reduce: Perform cumulative calculations, suitable for aggregation operations.
  • Applicable Scenarios: Data transformation, filtering, and aggregation tasks, especially advantageous in parallel computing or function composition. However, note that readability may suffer; complex logic might be better suited for regular loops or comprehensions.