Menu Close

Map Module in Python …FcuktheCode

The map function is the simplest one among Python built-ins used for functional programming. map() applies a specified function to each element in an iterable :

anime = ['Naruto', 'Bleach', 'One Piece']
print(map(len, anime))

#Output:  <map object at 0x7f94e082b0f0>

The result can be explicitly converted to a list.

anime = ['Naruto', 'Bleach', 'One Piece']
List_1 = list(map(len, anime))

print(List_1)

#Output:  [6, 6, 9]

map() can be replaced by an equivalent list comprehension or generator expression: ( Python 3 )

map_is = (len(series) for series in anime)

print(map_is)


#Output:  <generator object <genexpr> at 0x7f601f567360>

Mapping each value in an iterable

For example, you can take the absolute value of each element:

L = list(map(abs, (13, -12, 24, -20, 32, -23)))

print(L)

#Output:  [13, 12, 24, 20, 32, 23]

Anonymous function also support for mapping a list:

L = map(lambda x:x*2, [11, 22, 33, 44, 55])

print(list(L))

#Output:  [22, 44, 66, 88, 110]

or converting decimal values to percentages:

def to_percent(num):
    return num * 100

L = list(map(to_percent, [0.85, 0.95, 1.51, 1.01]))

print(L)


#Output:  [85.0, 95.0, 151.0, 101.0]

or converting dollars to euros (given an exchange rate):

from functools import partial
from operator import mul
rate = 0.9 # fictitious exchange rate
dollars = {'Curtain': 1000, 'jeans': 45, 'Wallet': 5000}

L = sum(map(partial(mul, rate), dollars.values()))

print(L)

#Output:  5440.5

functools.partial is a convenient way to fix parameters of functions so that they can be used with map instead of using lambda or creating customized functions.

Leave a Reply

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