SK RAJIBUL

Posted on

# Python's MAP/FILTER/REDUCE: Streamlining Data Manipulation in Seconds

Introduction:
Python offers powerful built-in functions for working with collections of data: MAP, FILTER, and REDUCE. In just 30 seconds, let's dive into what these functions do and how they can simplify your code.

## MAP:

The map function takes in 1) a function and 2) an iterable. The purpose of the function is to apply some sort of transformation to each element inside our iterable (think list). It then applies the function to every element in the iterable, and returns a new iterable.

# Double each number in a list
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)  # Output: [2, 4, 6, 8, 10]

## FILTER:

The filter function takes in 1) a function and 2) an iterable. The purpose of the function is to decide which iterables to keep or to discard in the new iterable. It does not apply any transformation on the elements.

mylist = [1, 2, 3, 4, 5, 6, 7, 8]

def larger5(n):
return n > 5

newlist = list(filter(larger5, mylist))
print(newlist)

# [6, 7, 8]
• each function call returns either True or False
• if True is returned, the original element is kept
• if False is returned, the original element is discarded

## REDUCE:

REDUCE applies a rolling computation to pairs of items in an iterable and returns a single result. It's like gradually combining items together until you get a final result. For example:

fruits = ['apple', 'orange', 'pear', 'pineapple']

return a + '-' + b

from functools import reduce