Member-only story

The Case for Python Maps

Martin McBride
3 min readMay 3, 2020

--

List comprehensions are great at what they do. But maps are something rather different, and they have their place too.

List comprehensions

A list comprehension is a clever little Python construct that can build a list from another list (or other iterable). For example:

k = [x + 3 for x in s]

This code takes an iterable sand adds 3 to each element, returning the result as a list. So if swas [1, 2, 3]the result would be [4, 5, 6].

We could do this with a the map function:

k = list(map(lambda x: x + 3, s))

This is obviously longer and uglier than the list comprehension. That is hardly surprising because this example is exactly what list comprehensions are for.

Maps

The map function has a different purpose, although there is some overlap. It is a functional programming construct that applies a function to one or more iterables, and returns a lazy iterator as a result.

The list comprehension example presupposes that we want a list as a result. But we don’t always need a list. For example, if we were intending to loop over kwe wouldn’t really care if it was a list, an iterator would do just as well. So our example would become:

k = map(lambda x: x + 3, s)

And if we are taking a functional approach, we might already have a curried add function, addcwhere addc(3)returns a new…

--

--

Martin McBride
Martin McBride

No responses yet