Temporary variables in list comprehensions
Serhiy Storchaka
storchaka at gmail.com
Mon Jan 9 05:41:44 EST 2017
On 09.01.17 05:53, Steven D'Aprano wrote:
> 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?
result = [(tmp, tmp + 1)
for tmp in (expensive_calculation(x) for x in data)]
You could also assign an internal generator expression to temporal
variable for readability if it is long.
gen = (expensive_calculation(x) for x in data)
result = [(tmp, tmp + 1) for tmp in gen]
More information about the Python-list
mailing list