How to Use Map Function in Pythonđź”—

Pavol Kutaj
2 min readApr 27, 2022

The aim of this pageđź“ťis to define the map function in Python and to discuss whether it is better to use the map function or python comprehension since usually they both can achieve identic results. No matter the decision, I believe one must be comfortable with both forms (one is core to functional programming, another core to pythonic style).

1. ITERATION/ITERABLEđź”—

  • lots of the ideas behind mapping were originally developed in the functional programming community
  • see prof. Abelson in the original 80s SICP lecture talking about map in the lecture on stream processing claiming it is an important element of conventional interfaces
  • in python specifically, map() is built on the concepts of iteratable and iterator

2. DEFINITIONđź”—

  1. take a list
  2. transform each element with the selected function
  3. return a new list
  • terminologically, one maps a function over a list/sequence to produce new values

3. LAZINESS

  • map evaluates lazily, i.e. not immediately, i.e. just-in-time;
  • values are produced only upon request by the caller
  • this request to evaluate is performed by one of the following:
    1) a constructor (e.g. list() )
    2) a loop ( while or for
    3) next keyword
  • this means they can be used to model infinite sequences
the returned object must be iterated upon to return values
>>> for o in map(ord, "The Quick brown fox"):
... print(o)
84
104
101
32
81
117
105
99
107
32
98
114
111
119
110
32
102
111
120

4. MULTIPLE INPUT SEQUENCESđź”—

  • you need to provide as many sequences as there are arguments in the map function
  • map() takes elements from a corresponding sequence for the call of the map function to produce each output value
  • map() terminates as soon as any of the input sequences is terminated
sizes = ['small', 'medium','large']
colors = ['red','green','blue']
names = ['paul','alexander','charles']

def combine(size,color,name):
return(f"{size} + {color} + {name}")

print(list(map(combine,sizes,colors,names)))

# ['small + red + paul', 'medium + green + alexander', 'large + blue + charles']

5. COMPREHENSIONSđź”—

  • map provides similar functionality to comprehensions
  • the following produce identical output
[str(i) for i in range(5)]
list(map(str,range(5)))
# ['0','1','2','3','4','5']
  • their performance is similar
  • readability of a matter of taste, there are fans of comprehensions and there are fans of functional-style using map explicitly

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com