1

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 ?

2
  • 2
    Try to print the result of that map Commented Feb 25, 2019 at 12:58
  • 2
    You forgot to convert the map object to a list Commented Feb 25, 2019 at 12:58

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.