Temporary variables in list comprehensions
auriocus at gmx.de
Mon Jan 9 14:43:01 EST 2017
Am 09.01.17 um 04:53 schrieb Steven D'Aprano:
> 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...
I think this is quite clear, and a useful feature, only that Python
makes it unnecessarily hard. In Haskell, there is a "let" clause, which
would allow to write it as:
[let tmp = expensive_calc(x), (tmp, tmp+1) for x in data]
or better readable using "with" or "where" as in
[(tmp, tmp + 1) with tmp = expensive_calc(x) for x in data]
or similar. So maybe that's a PEP to extend the list comprehension syntax?
More information about the Python-list