Temporary variables in list comprehensions
Chris Angelico
rosuav at gmail.com
Sun Jan 8 23:09:33 EST 2017
On Mon, Jan 9, 2017 at 2:53 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> [(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...
A horrible hack on par with abusing a recursive function's arguments
for private variables. Much better would be to refactor the append
part:
def this_and_one(value):
return value, value + 1
[this_and_one(expensive_calculation(x)) for x in data]
ChrisA
More information about the Python-list
mailing list