How to Use Map Function in Pythonđź”—

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đź”—

  • 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. transform each element with the selected function
  2. return a new list
  • terminologically, one maps a function over a list/sequence to produce new values

3. LAZINESS

  • 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đź”—

  • 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đź”—

  • 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

--

--

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com