Difference Between map, filter, and reduce in Python

Difference Between map, filter, and reduce in Python

map(), filter(), and reduce() are functional programming tools in Python used for processing iterables like lists

Map : It applies each element from the iterables and returns the new iterables

map(function, iterable)

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

Use case : When you want to change or modify the elements from the list


Filter: Used to filter the elements from the list based on the certain condition function if its TRUE

filter(function, iterable)

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

Use case : When you want to extract elements that meet a condition.



NOTE : Filter and Map returns in obj that needs to convert to the iterable format like list tuple etc.



Reduce: Reduces the iterable to a single value by applying a function cumulatively.

reduce(function, iterable)

from functools import reduce

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

Use case: When you need to combine all elements into a single result (e.g., sum, product, etc.).




要查看或添加评论,请登录

Harshwardhan Jadhav的更多文章

社区洞察

其他会员也浏览了