[Python-ideas] Temporary variables in comprehensions
Chris Barker - NOAA Federal
chris.barker at noaa.gov
Thu Feb 15 20:50:51 EST 2018
> Setting a new comprehension variable is not likely to be free, and may even be
> more costly than calling f(x) twice if f() is a cheap expression:
>
> [x+1 + some_func(x+1) for x in range(10)]
>
> could be faster than
>
> [y + some_func(y) for x in range(10) let y = x + 1]
A bit of a nit — function call overhead is substantial in python, so
if that is an actual function, rather than a simple expression, it’ll
likely be slower to call it twice for any but trivially small
iterables.
> [(y, y**2) let y = x+1 for x in (1, 2, 3, 4)]
Do we need the let?
[ g(y) for y = f(x) for c in seq]
Or, with expressions:
[y + y**2 for y = x+1 for x in (1,2,3)]
Maybe that would be ambiguous— I haven’t thought carefully about it.
-CHB
More information about the Python-ideas
mailing list