0% found this document useful (0 votes)
5 views2 pages

Python Functions: map, filter, reduce

The document explains three functions in Python: map(), filter(), and reduce(). map() transforms each element of a sequence using a function, filter() selects elements that meet a condition, and reduce() accumulates a result by repeatedly applying a function. Each function is illustrated with examples demonstrating their usage with lists of numbers.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Python Functions: map, filter, reduce

The document explains three functions in Python: map(), filter(), and reduce(). map() transforms each element of a sequence using a function, filter() selects elements that meet a condition, and reduce() accumulates a result by repeatedly applying a function. Each function is illustrated with examples demonstrating their usage with lists of numbers.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

map()

Purpose: Transform each element of a sequence using a function.

Input: function + iterable

Output: new iterable (with the same length, transformed values)

Example: Square every number in a list

numbers = [1, 2, 3, 4, 5]

squared = list(map(lambda x: x**2, numbers))

print(squared) # [1, 4, 9, 16, 25]

🔹 2. filter()

Purpose: Select elements from a sequence that satisfy a condition.

Input: function (returns True/False) + iterable

Output: new iterable (with fewer or equal elements)

Example: Keep only even numbers

numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, numbers))

print(evens) # [2, 4]

🔹 3. reduce()

Purpose: Repeatedly apply a function to accumulate a result.

Input: function (with two arguments) + iterable

Output: single value

Example: Find the product of all numbers

from functools import reduce

numbers = [1, 2, 3, 4, 5]

product = reduce(lambda x, y: x * y, numbers)

print(product) # 120

You might also like