FenryrMKIII
FenryrMKIII

Reputation: 1198

Map vs List vs loop in python 3.7

When reading articles about the speed of Loop vs List comprehension vs Map, I usually find that list comprehension if faster than map when using lambda functions.

Here is a test I am running:

import timeit

def square(range):
    squares = []
    for number in range:
        squares.append(number*number)
    return squares

print(timeit.timeit('map(lambda a: a*a, range(100))', number = 100000))
print(timeit.timeit('[a*a for a in range(100)]', number = 100000))
print(timeit.timeit('square(range(100))', 'from __main__ import square', number = 100000))

and the results :

0.03845796199857432
0.5889980600004492
0.9229458660011005

so Map is the clear winner altough using a lambda function. Has there been a change in python 3.7 causing this notable speed boost ?

Upvotes: 1

Views: 4956

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

First of all, to have a fare comparison you have to convert the result of the map function to list. map in Python 3.X returns an iterator object not a list. Second of all, in CPython implementation built in functions are actually wrappers around c functions which makes them faster than any Python code with same functionality, although when you use lambda inside a built-in function you're actually breaking the chain and this will make it approximately as fast as a Python code.

Another important point is that list comprehension is just a syntactic sugar around a regular loop and you can use it to avoid extra function calls like appending to lists, etc.

Upvotes: 3

Related Questions