Member-only story
The Case for Python Maps
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 s
and adds 3 to each element, returning the result as a list. So if s
was [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 k
we 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, addc
where addc(3)
returns a new…