Temporary variables in list comprehensions

Tim Chase python.list at tim.thechases.com
Mon Jan 9 12:11:29 EST 2017


On 2017-01-09 04:59, Rustom Mody wrote:
> What happens when the expensive is on an inner generator?
> Something like:
> 
> [expensive₂(y)  for x in data for y in foo(x)]
> 
> [The ₂ representing the 2 or more occurrences in Steven's eg]

Well, if I understand your question correctly, the goal would be to
execute each expensive operation only once, regardless of how many
expensive functions you execute:

  [(x, a, b, x+1, a+1, b+1)
   for x, a, b
   in (
     x,
     expensive_a(x),
     expensive_b(x),
     for x
     in data
     )
   # if x > 42 # optionally test against values
   ]

-tkc






More information about the Python-list mailing list