Temporary variables in list comprehensions

Tim Chase python.list at tim.thechases.com
Thu Apr 6 16:22:49 EDT 2017


On 2017-04-06 14:56, Vincent Vande Vyvre wrote:
> With two passes
> 
> e = [expensive_calculation(x) for x in data]
> final = [(x, y+1) for x, y in zip(e, e)]

Using a generator it can be done in one pass:

 final = [
   (value, tmp, tmp+1)
   for value, tmp
   in (
     (x, expensive_calculation(x))
     for x in data
     )
   ]

The above makes use of the original value as well at top level
(whether you need it for "if" filtering, or in your final tuple
result). If you don't care, you can discard it

 final = [
   (tmp, tmp+1)
   for tmp
   in (
     expensive_calculation(x)
     for x in data
     )
   ]

-tkc





More information about the Python-list mailing list