Python provides three powerful built-in (or semi-built-in) functional programming tools:
β
map() β Transforms data
β
filter() β Filters data
β
reduce() β Aggregates data
They are often used with lambda functions to write clean, concise, and efficient code.
Letβs go through each one step by step π
πΉ 1. map() Function
β Purpose:
map()applies a function to each element of an iterable (like a list or tuple) and returns a map object (which can be converted into a list or other iterable).
β Syntax:
map(function, iterable)π§© Example 1 β Square of Each Number
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares)Output:
[1, 4, 9, 16, 25]β
The lambda function lambda x: x**2 is applied to each number.
π§© Example 2 β Convert Strings to Uppercase
names = ["alice", "bob", "charlie"]
upper_names = list(map(str.upper, names))
print(upper_names)Output:
['ALICE', 'BOB', 'CHARLIE']β
Here, we used str.upper directly instead of a lambda.
π§© Example 3 β Add Two Lists Element-wise
a = [1, 2, 3]
b = [4, 5, 6]
result = list(map(lambda x, y: x + y, a, b))
print(result)Output:
[5, 7, 9]β
map() can take multiple iterables if the function accepts multiple arguments.
πΉ 2. filter() Function
β Purpose:
filter()selects elements from an iterable based on a condition (True/False) and returns only those elements that satisfy the condition.
β Syntax:
filter(function, iterable)- The function must return
TrueorFalse. - Only elements where the function returns
Trueare kept.
π§© Example 1 β Filter Even Numbers
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)Output:
[2, 4, 6]β Keeps only even numbers.
π§© Example 2 β Filter Strings Starting with βAβ
names = ["Alice", "Bob", "Amanda", "Adam", "Charlie"]
a_names = list(filter(lambda x: x.startswith('A'), names))
print(a_names)Output:
['Alice', 'Amanda', 'Adam']β Keeps names starting with βAβ.
π§© Example 3 β Remove Empty Strings
strings = ["hello", "", "world", "", "python"]
non_empty = list(filter(None, strings))
print(non_empty)Output:
['hello', 'world', 'python']β
Using None as the function removes all βfalsyβ values ("", 0, None, etc.)
πΉ 3. reduce() Function
β Purpose:
reduce()applies a function cumulatively to all elements in a sequence, reducing it to a single value.
β οΈ Itβs not a built-in β you must import it from the functools module.
β Syntax:
from functools import reduce
reduce(function, iterable[, initializer])functiontakes two arguments.- Applies it repeatedly to reduce the sequence to one value.
π§© Example 1 β Sum of All Elements
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total)Output:
15β Works like:
(((1 + 2) + 3) + 4) + 5 β 15π§© Example 2 β Find Maximum Element
from functools import reduce
numbers = [5, 8, 2, 10, 3]
maximum = reduce(lambda x, y: x if x > y else y, numbers)
print(maximum)Output:
10β Compares elements pairwise to find the max.
π§© Example 3 β Multiply All Elements
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)Output:
24β
Equivalent to 1 * 2 * 3 * 4.
π§© Example 4 β Using an Initial Value
from functools import reduce
numbers = [1, 2, 3]
total = reduce(lambda x, y: x + y, numbers, 10)
print(total)Output:
16β The initializer (10) is added as the starting value.
πΉ 4. Combining map(), filter(), and reduce()
You can combine all three for complex data processing.
π§© Example β Double Even Numbers and Find Their Sum
from functools import reduce
numbers = [1, 2, 3, 4, 5, 6]
# Step 1: Filter even numbers
evens = filter(lambda x: x % 2 == 0, numbers)
# Step 2: Double them
doubles = map(lambda x: x * 2, evens)
# Step 3: Sum them
result = reduce(lambda x, y: x + y, doubles)
print("Final Result:", result)Output:
Final Result: 24β Step-by-step:
Even numbers β [2, 4, 6]
Doubled β [4, 8, 12]
Sum β 24πΉ 5. Practical Example β Word Processing
Count Total Length of Words Starting with βPβ
from functools import reduce
words = ["Python", "Programming", "is", "Powerful", "and", "Popular"]
# Filter words starting with P
p_words = filter(lambda w: w.startswith('P'), words)
# Map to word lengths
lengths = map(len, p_words)
# Reduce to total length
total_length = reduce(lambda x, y: x + y, lengths)
print("Total Length:", total_length)Output:
Total Length: 26β
"Python" (6) + "Programming" (11) + "Powerful" (8) + "Popular" (7) β 32
(Example output may vary depending on words used.)
πΉ 6. Comparison Summary
| Function | Purpose | Returns | Common Use |
|---|---|---|---|
map() | Transform all elements | New iterable (map object) | Apply operation to each item |
filter() | Select some elements | New iterable (filter object) | Keep elements that match condition |
reduce() | Aggregate all elements | Single value | Summation, product, max/min |
β Example Recap
| Task | Code | Output |
|---|---|---|
| Square numbers | map(lambda x: x**2, [1,2,3]) | [1, 4, 9] |
| Filter even numbers | filter(lambda x: x%2==0, [1,2,3,4]) | [2, 4] |
| Sum all numbers | reduce(lambda x,y: x+y, [1,2,3,4]) | 10 |
π§Ύ Summary Table
| Function | Description | Example | Output |
|---|---|---|---|
map() | Applies a function to all elements | map(lambda x: x*2, [1,2,3]) | [2,4,6] |
filter() | Keeps elements that satisfy a condition | filter(lambda x: x>2, [1,2,3,4]) | [3,4] |
reduce() | Reduces a list to one value | reduce(lambda x,y:x*y, [1,2,3,4]) | 24 |
β In short:
map()β transforms every elementfilter()β selects specific elementsreduce()β combines all elements into one result- Often used with lambda functions for cleaner, functional-style code.
π§© Final Example (All-in-One):
from functools import reduce
numbers = [1, 2, 3, 4, 5, 6]
# Step 1: Keep even numbers
# Step 2: Square them
# Step 3: Sum the result
result = reduce(
lambda x, y: x + y,
map(lambda x: x**2, filter(lambda x: x % 2 == 0, numbers))
)
print("Sum of squares of even numbers:", result)Output:
Sum of squares of even numbers: 56β Explanation:
Even numbers β [2, 4, 6]
Squares β [4, 16, 36]
Sum β 56π§ Final Takeaway:
map(),filter(), andreduce()are Pythonβs functional programming tools
that let you transform, filter, and aggregate data in a clean and concise way β
making your code more expressive, elegant, and efficient.
