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

RMAG news

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]

def add(a, b):
return a + + b

from functools import reduce

result = reduce(add, fruits)
print(result)

# apple-orange-pear-pineapple

add(‘apple’, ‘orange’) returns ‘apple-orange’
add(‘apple-orange’, ‘pear’) returns ‘apple-orange-pear’
add(‘apple-orange-pear’, ‘pineapple’) returns ‘apple-orange-pear-pineapple’
And this is why we get ‘apple-orange-pear-pineapple’ in the end

Conclusion:
In just 100 seconds, you’ve learned about Python’s MAP, FILTER, and REDUCE functions. These powerful tools can help you manipulate data in a concise and expressive way, making your code more readable and efficient. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *