possibly trivial newbie list/array question

Paul Rubin phr-n2001 at nightsong.com
Wed Aug 22 12:23:22 CEST 2001

```"Alex Martelli" <aleax at aleax.it> writes:
> So, the nifty list-comprehension is at least as
> fast as the map+lambda combo, and presumably a
> bit faster, about 10% -- at least on this box
> (Python 2.1.1, WinNT4, Pentium3-300, lots of RAM).

I just tried your example in Python 2.1.1, Linux, P3-750, lots of ram,
but with a 100 element list instead of 3 elements.

a = map(lambda x: x+1.0, range(100))

Results (running each method 10,000 times like in your example):

map(lambda x: 4.0*x, a)       1.97 seconds
[4.0*x for x in a]            3.57 seconds

I don't know why the list comprehension is slower than the map/lambda
for this larger list.

I also used the occasion to download NumPy and try it out.  As
expected, it's a lot faster than either of the above methods, since it
doesn't have interpreter overhead at every one of the multiplications:

import Numeric
na = array(a)

start = time.clock()
for i in range(10000):
junk = 4.0 * na
stend = time.clock ()
print "%.2f"%(stend-start)

Result: 0.31 seconds.  So NumPy is by far the fastest of the methods.

```