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 - How to retrieve a variable from the Apache configuration inside the module? -

c# - Constructor arguments cannot be passed for interface mocks -

python - malformed header from script index.py Bad header -