Temporary variables in list comprehensions

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jan 10 20:10:13 EST 2017


On Tuesday 10 January 2017 00:12, Antoon Pardon wrote:

> Op 09-01-17 om 04:53 schreef Steven D'Aprano:
>> 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:
[...]
>> I can't decide whether that's an awesome trick or a horrible hack...
> 
> Maybe this in an occasion to use your recipe.
> 
> http://code.activestate.com/recipes/580625-collection-pipeline-in-python/
> 
> result = data | Map(expensive_calculation) | Map(lambda tmp: (tmp, tmp + 1))
> | List
> 


Indeed :-)



-- 
Steven
"Ever since I learned about confirmation bias, I've been seeing 
it everywhere." - Jon Ronson




More information about the Python-list mailing list