How does Python perform during a list comprehension? -


def thing(mode, data):     return [         item item in data         if {             'large': lambda item: item > 100,             'small': lambda item: item < 100,         }[mode](item)     ] 

this list comprehension generates dictionary of lambdas, retrieves 1 lambda via mode argument , applies list item being processed. question this: performance characteristics of this?

is entire dictionary created scratch during each iteration of listcomp? or created once , used on each item?

is entire dictionary created scratch during each iteration of listcomp

yes.

or created once , used on each item?

no.


fortunately, in case (and others can think of), it's easy build dict ahead of time:

 d = {         'large': lambda item: item > 100,         'small': lambda item: item < 100,       }  return [item item in data if d[mode](item)] 

or even,

func = {         'large': lambda item: item > 100,         'small': lambda item: item < 100,         }[mode] return [item item in data if func(item)] 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -