Temporary variables in list comprehensions

Vincent Vande Vyvre vincent.vande.vyvre at telenet.be
Thu Apr 6 08:56:41 EDT 2017


Le 06/04/17 à 14:25, Piet van Oostrum a écrit :
> Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:
>
>> Suppose you have an expensive calculation that gets used two or more times in a
>> loop. The obvious way to avoid calculating it twice in an ordinary loop is with
>> a temporary variable:
>>
>> result = []
>> for x in data:
>>      tmp = expensive_calculation(x)
>>      result.append((tmp, tmp+1))
>>
>>
>> But what if you are using a list comprehension? Alas, list comps don't let you
>> have temporary variables, so you have to write this:
>>
>>
>> [(expensive_calculation(x), expensive_calculation(x) + 1) for x in data]
>>
>>
>> Or do you? ... no, you don't!
>>
>>
>> [(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...
> It is a poor man's 'let'. It would be nice if python had a real 'let'
> construction. Or for example:
>
> [(tmp, tmp + 1) for x in data with tmp = expensive_calculation(x)]
>
> Alas!

With two passes

e = [expensive_calculation(x) for x in data]
final = [(x, y+1) for x, y in zip(e, e)]

Vincent





More information about the Python-list mailing list