[go: up one dir, main page]

0% found this document useful (0 votes)
26 views28 pages

Map, Filter, Reduce

Uploaded by

Aamna Raza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views28 pages

Map, Filter, Reduce

Uploaded by

Aamna Raza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

map(), filter(), reduce()

• Map in Python is a function that works as an iterator to return a result


after applying a function to every item of an iterable (tuple, lists, etc.).
• It is used when you want to apply a single transformation function to
all the iterable elements.
• The iterable and function are passed as arguments to the map in
Python.
• The syntax of the Python map() function is:
map(function, iterables)
• function: It is the transformation function through which all the items
of the iterable will be passed.
• iterables: It is the iterable (sequence, collection like list or tuple) that
you want to map.
def mul(i):
return i * i
# Using the map function
x = map(mul, (3, 5, 7, 11, 13))
print (x)
print(list(x))
• The map in Python takes a function and an iterable/iterables.
• It loops over each item of an iterable and applies the transformation
function to it.
• Then, it returns a map object that stores the value of the transformed
item.
• The input function can be any callable function, including built-in
functions, lambda functions, user-defined functions, classes, and
methods.
Using map() with built-in functions
example = ["Welcome", "to", "UPES"]
x = list(map(len, example))
print(x)
import math
num = [9, 36, 49, 81, 121]
x = (map(math.sqrt, num))
print(list(x))
Using Map in Python as an Iterator

• You can use the Python map() function with a String.


• While using the map() with a String, the latter will act like an array.
• You can then use the map() function as an iterator to iterate through all
the string characters.
def upper(n):
return n.upper()
stri = "This is Python"
upd_list = map(upper, stri)
print(upd_list)
print(list(upd_list))
map() with tuple
def example(s):
return s.upper()
tuple_exm = ('this','is','map','in','python', 'article')
upd_tup = map(example, tuple_exm)
print(upd_tup)
print(tuple(upd_tup))
map() with dictionary
car_dict ={'a': 'Mercedes-Benz', 'b': 'BMW', 'c': 'Ferrari', 'd':
'Lamborghini', 'e': 'Jeep'}
# adding an '_' to the end of each value
car_dict = dict(map(lambda x: (x[0], x[1] + '_'), car_dict.items() ))
print('The modified dictionary is : ')
print(car_dict)
map() with set
def example(i):
return i%3
set_exm = {33, 102, 62, 96, 44, 28, 227}
upd_itms = map(example, set_exm)
print(upd_itms)
print(set(upd_itms))
Multiple Input Iterables With map()
• If you supply multiple iterables to map(), then the transformation
function must take as many arguments as iterables you pass in.
• Each iteration of map() will pass one value from each iterable as an
argument to function.
• The iteration stops at the end of the shortest iterable.
first_it = [1, 2, 3,4]
second_it = [4, 5, 6, 7]
list(map(pow, first_it, second_it))

Output: [1,32,729]
pow() takes two arguments, x and y, and returns x to the power of y.
In the first iteration, x will be 1, y will be 4, and the result will be 1.
In the second iteration, x will be 2, y will be 5, and the result will be 32,
and so on.
The final iterable is only as long as the shortest iterable, which is first_it
in this case.
Transforming Iterables of Strings With
Python’s map()
• Using the Methods of str

string_it = ["processing", "strings", "with", "map"]


list(map(str.capitalize, string_it))
['Processing', 'Strings', 'With', 'Map']

list(map(str.upper, string_it))
['PROCESSING', 'STRINGS', 'WITH', 'MAP']

list(map(str.lower, string_it))
['processing', 'strings', 'with', 'map']
• Using math operations
def powers(x):
return x ** 2, x ** 3
numbers = [1, 2, 3, 4]
list(map(powers, numbers))
• Type conversion
# Convert to floating-point
list(map(float, ["12", "3", "-15"]))

# Convert to integer
list(map(int, ["12.5", "3.0", "-15"]))
Combining map() With Other Functional
Tools
• Sometimes we need to process an input iterable and return another
iterable that results from filtering out unwanted values in the input
iterable.
• In that case, Python’s filter() can be a good option for you.
• filter() is a built-in function that takes two positional arguments:
• function will be a predicate or Boolean-valued function, a function
that returns True or False according to the input data.
• iterable will be any Python iterable.
• filter() yields the items of the input iterable for which function returns
True.
• If you pass None to function, then filter() uses the identity function.
• This means that filter() will check the truth value of each item in
iterable and filter out all of the items that are false.
import math
def is_positive(num):
return num >= 0
def sanitized_sqrt(numbers):
cleaned_iter = map(math.sqrt, filter(is_positive, numbers))
return list(cleaned_iter)

sanitized_sqrt([25, 9, 81, -16, 0])


is_positive() is a predicate function that takes a number as an argument
and returns True if the number is greater than or equal to zero.
You can pass is_positive() to filter() to remove all the negative numbers
from numbers.
So, the call to map() will process only positive numbers and math.sqrt()
won’t give you a ValueError.
map() and reduce()
• Python’s reduce() is a function that lives in a module called functools in the
Python standard library.
• reduce() is another core functional tool in Python that is useful when you need
to apply a function to an iterable and reduce it to a single cumulative value.
• This kind of operation is commonly known as reduction or folding. reduce()
takes two required arguments:
• function can be any Python callable that accepts two arguments and returns a
value.
• iterable can be any Python iterable.
Note: reduce() will apply function to all the items in iterable and cumulatively
compute a final value.
• The reduce() is very handy for processing iterables without
programming explicit For loops.
• This reduce() function is similar to a for loop in Python, reduce() is an
in-built function and is programmed in C language, which makes it
much more optimized and faster.
• The function passed as an argument is applied to the first two
elements of the iterable.
• After this, the function is applied to the previously generated result
and the next element in the iterable.
• This process continues until the whole iterable is processed.
• The single value is returned as a result of applying the reduce
function on the iterable.
from functools import reduce
# calculates the product of two elements
def product(x,y):
return x*y
ans = reduce(product, [2, 5, 3, 7])
print(ans)
import functools
# importing operator module
import operator
dummy = [-1, 5, 10, 6, 3]
# Use reduce to calculate the sum of the list along with add operator function
print("The sum using add operator function is", functools.reduce(operator.add,
dummy))

# using concat operator function to join strings


print(functools.reduce(operator.concat, ["Scaler ", "Academy"]))
from functools import reduce
# pre-defined function to calculate minimum
def mini(a, b):
return a if a < b else b
# pre-defined function to calculate maximum
def maxi(a, b):
return a if a > b else b
nums = [3, 5, 2, 4, 7, 1]
# passing both functions in the reduce along with nums as iterable
print('The minimum in the given list is', reduce(mini, nums))
print('The maximum in the given list is', reduce(maxi, nums))

You might also like