Mapping each value in an iterable

suggest change

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

list(map(abs, (1, -1, 2, -2, 3, -3))) # the call to `list` is unnecessary in 2.x
# Out: [1, 1, 2, 2, 3, 3]

Anonymous function also support for mapping a list:

map(lambda x:x*2, [1, 2, 3, 4, 5])
# Out: [2, 4, 6, 8, 10]

or converting decimal values to percentages:

def to_percent(num):
    return num * 100

list(map(to_percent, [0.95, 0.75, 1.01, 0.1]))
# Out: [95.0, 75.0, 101.0, 10.0]

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

from functools import partial
from operator import mul

rate = 0.9  # fictitious exchange rate, 1 dollar = 0.9 euros
dollars = {'under_my_bed': 1000,
           'jeans': 45,
           'bank': 5000}

sum(map(partial(mul, rate), dollars.values()))
# Out: 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents