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

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -