How to Use Map Function in Pythonđź”—

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

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']
  • readability of a matter of taste, there are fans of comprehensions and there are fans of functional-style using map explicitly

--

--

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

Pavol Kutaj

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