How to use Map in python basic tutorial

  • 2020-05-24 05:48:25
  • OfStack

Python Map

Map maps a function to all the elements of an input list. The specification for Map is: map(function_to_apply, list_of_inputs)
Most of the time, we need to pass each of the 1's in the list to a function and collect the output. Such as:


items = [1, 2, 3, 4, 5] 
squared = [] 
for i in items: 
  squared.append(i**2) 

Using Map allows us to solve this problem in a simpler way.


items = [1, 2, 3, 4, 5] 
squared = list(map(lambda x: x**2, items)) 

Most of the time, we will use the anonymous function lambda in python to match map. Not only for the input of list 1, but also for the function of list 1.


def multiply(x): 
  return (x*x) 
def add(x): 
  return (x+x) 
funcs = [multiply, add] 
for i in range(5): 
  value = list(map(lambda x: x(i), funcs)) 
  print(value) 

The output of the above program is:


# Output: 
# [0, 0] 
# [1, 2] 
# [4, 4] 
# [9, 6] 
# [16, 8] 

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: