Temporary variables in list comprehensions

Paul Moore p.f.moore at gmail.com
Tue Jan 10 09:32:31 EST 2017


On Monday, 9 January 2017 03:53:37 UTC, Steven D'Aprano  wrote:
> Suppose you have an expensive calculation that gets used two or more times
> in a loop.

[...]

> [(tmp, tmp + 1) for x in data for tmp in [expensive_calculation(x)]]
> 
> I can't decide whether that's an awesome trick or a horrible hack...

My immediate reaction is that it depends on the constraints that made it important for you to use a comprehension rather than an explicit loop in the first place.

For a toy example like this it's obviously a horrible hack, and you should simply make an explicit loop:

    result = []
    for x in data:
      # Don't recalculate this value, as it's expensive!
      val = expensive_calculation(x)
      result.append((val, val+1))

In a real world case, maybe there's a good reason why you'd prefer to stick with a comprehension. In that case, you look at trade-offs like

    def intermediate_tuple(val): return val, val+1
    [intermediate_tuple(x) for x in data]

or

    [(lambda val: (val, val+1))(x) for x in data]

or your version.

All have their own unique uglinesses, as does the explicit loop. Personally my preferences would be the explicit loop, then the intermediate_tuple function, in that order.

Paul


More information about the Python-list mailing list