Skip to content

Python map vs list comprehension | Difference

  • by

As per speed comparison between Python Map and list comprehension map may be microscopically faster in some cases (when you’re NOT making a lambda for the purpose, but using the same function in the map and a list comp).

List comprehensions may be faster in other cases and most (not all) Pythonistas consider them more direct and clearer.

Python map vs list comprehension

Let’s see them one by one different on both.

Definitions and uses:

Map function:- The map function takes an Expression and an Iterable. The output will be an Iterable object where the expression will work on each element of the given Iterable. The output of each expression will be an element of the resultant Iterable. 

List Comprehension:- Python List Comprehension is used for creating a list where each element is generated by applying a simple formula to the given list. 

Syntax and code:

List comprehension code is more concise and easier to read as compared to the map function.

Map function:-

map( expression, iterable) 
# function to double the number
def num(n):
    return n * 2


lst = [1, 2, 3, 4, 5]

# creates a map object
x = map(num, lst)

# Print list
print(list(x))

Output:

Python map vs list comprehension

List Comprehension:

[ expression for item in list if conditional ]
lst = [1, 2, 3, 4, 5]

x = [i * 2 for i in lst]
print(x)

Output: [2, 4, 6, 8, 10]

Speed and Performance comparison

An example of the tiny speed advantage of the map when using exactly the same function:

$ python -m timeit -s'xs=range(10)' 'map(hex, xs)'
100000 loops, best of 3: 4.86 usec per loop
$ python -m timeit -s'xs=range(10)' '[hex(x) for x in xs]'
100000 loops, best of 3: 5.58 usec per loop

An example of how performance comparison gets completely reversed when a map needs a lambda:

$ python -m timeit -s'xs=range(10)' 'map(lambda x: x+2, xs)'
100000 loops, best of 3: 4.24 usec per loop
$ python -m timeit -s'xs=range(10)' '[x+2 for x in xs]'
100000 loops, best of 3: 2.32 usec per loop

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this Python topic

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading