0

map( lambda x: len(x), aLotOfData)

I am writing some code similar to above, will it actually be slower if I put in the lambda def in the same line? or I should assign to to a variable f to avoid evolve the lambda def in every iteration or python actually smart enough to cache it?

Henrik
  • 23,186
  • 6
  • 42
  • 92
John
  • 2,107
  • 3
  • 22
  • 39
  • thansk bakuriu, my example is kind of over-simplified. the lambda was doing more than just len(). was thinking if there is any significant harm by using lambda as sometime it does have a better readibility – John May 15 '13 at 09:22

1 Answers1

1

The lambda is only evaluated once(converted to a code object), so there's no need of of assigning it to a variable.

>>> import dis
>>> def func():
...    map( lambda x: len(x), aLotOfData) 
...    
>>> dis.dis(func)
  2           0 LOAD_GLOBAL              0 (map)
              3 LOAD_CONST               1 (<code object <lambda> at 0x31c3d30, file "<ipython-input-30-27b0b12b0965>", line 2>)
              6 MAKE_FUNCTION            0
              9 LOAD_GLOBAL              1 (aLotOfData)
             12 CALL_FUNCTION            2
             15 POP_TOP             
             16 LOAD_CONST               0 (None)
             19 RETURN_VALUE  

But as map is slow with lambda's so should use a list comprehension or generator expression(if you want an iterator) here.

[len(x) for x in aLotOfData]

or define a full function, which is more readable:

def my_func(x):
   #do something with x
   return something

[my_func(x) for x in aLotOfData]

Which is more preferable to use in Python: lambda functions or nested functions ('def')?

Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • thanks, but why 'map is slow with lambda' if the lambda is only evaluated once? I thought map is just doing exactly the same as [len(x) for x in aLotOfData] with with a additional func all? I can imagine it is slower (as it is with more stack operation) but it might not be slow? or I am missing something very basis? thanks – John May 15 '13 at 09:19
  • @JohnZ The answer is a little misleading. `[f(x) for x in l]` is only faster than `map(lambda x: f(x), l)` because of the `lambda`, but it's a daft comparison. `map` is always faster than a list comprehension given identical expressions, so `map(f, l)` is faster than `[f(x) for x in l]`, and `map(lambda x: f(x), l)` is faster than `[(lambda x: f(x))(x) for x in l]`. – Aya May 15 '13 at 10:36