For map/lambda expression with array a = [1, 2, 3, 4]
:
f = map(lambda x : x + 32, a)
Seems I can simplify write as:
f = [x + 32 for x in a]
I am wondering whether there is any difference.
For map/lambda expression with array a = [1, 2, 3, 4]
:
f = map(lambda x : x + 32, a)
Seems I can simplify write as:
f = [x + 32 for x in a]
I am wondering whether there is any difference.
lambda
tends to be slower cause of the function's overhead. Also lambdas tend to make code more difficult to read. You can also time it:
#!/usr/bin/env python
import time
a = [1, 2, 3, 4]
t1 = time.time()
f = map(lambda x : x + 32, a)
t2 = time.time()-t1
print t2
t3 = time.time()
g = [x + 32 for x in a]
t4 = time.time()-t3
print t4
This code returned:
7.86781311035e-06
2.14576721191e-06
Also I tried the same thing for larger lists and the time taken is almost double for lambda
expression.
python -m timeit '[x + 32 for x in range(100000)]'
>> 100 loops, best of 3: 6.67 msec per loop
python -m timeit 'map(lambda x : x + 32, range(100000))'
>> 100 loops, best of 3: 12.5 msec per loop
which is huge difference in performance.