Thursday 23 September 2021

Python: map(): apply function to every element of iterable

‘map()’ function is used to apply a function to the every element of iterable.

 

Signature

map(function, iterable, ...)

 

map() function return a map object, use list() function to convert it to the list.

 

Example

cube_numbers = map(lambda x : x ** 3, numbers)

 

map_demo_1.py

numbers = [1, 2, 3, 4, 5]

twice_numbers = map(lambda x : 2 *x, numbers)
square_numbers = map(lambda x : x ** 2, numbers)
cube_numbers = map(lambda x : x ** 3, numbers)

print('numbers -> ', numbers)
print('twice_numbers -> ', list(twice_numbers))
print('square_numbers -> ', list(square_numbers))
print('cube_numbers -> ', list(cube_numbers))

 

Output

numbers ->  [1, 2, 3, 4, 5]
twice_numbers ->  [2, 4, 6, 8, 10]
square_numbers ->  [1, 4, 9, 16, 25]
cube_numbers ->  [1, 8, 27, 64, 125]

 

If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel.

 

map_demo_2.py
numbers = [1, 2, 3, 4, 5]

def calc(x, y):
    return x**2, x**3

square_and_cubes = map(calc, numbers, numbers)

print('numbers -> ', numbers)
print('square_and_cubes -> ', list(square_and_cubes))

 

Output

numbers ->  [1, 2, 3, 4, 5]
square_and_cubes ->  [(1, 1), (4, 8), (9, 27), (16, 64), (25, 125)]

 


  

Previous                                                    Next                                                    Home

No comments:

Post a Comment