How to Get Rid of Python’s Map Function With List Comprehension

Rate this post

You may have read that Python’s godfather, Guido van Rossum, doesn’t like the map() function too much. He argues that it can be easily replaced with list comprehension which is not only faster but also more readable and shorter. Here’s an example:

# Python Puzzle
xs = list(range(10))

list_1 = list(map(lambda x: x*x, xs))
list_2 = [x*x for x in xs]

print(list_1 == list_2)

You can solve the puzzle on the interactive Finxter app before reading on to test your Python skills:

Solve this puzzle in interactive mode.

As you may have guessed, both lists list_1 and list_2 contain the same data: a series of squared values.

The puzzle shows two ways to achieve the same result. Either you can use map(function, list) and convert the resulting map object to a list or you iterate over each item with a list comprehension. Both ways lead to the same result, thus the output is True.

Leave a Comment