Idiomatic Python for incrementing pairs

Jason Swails jason.swails at gmail.com
Fri Jun 7 23:46:22 EDT 2013


On Fri, Jun 7, 2013 at 10:32 PM, Tim Chase <python.list at tim.thechases.com>wrote:

> Playing around, I've been trying to figure out the most pythonic way
> of incrementing multiple values based on the return of a function.
> Something like
>
>   def calculate(params):
>     a = b = 0
>     if some_calculation(params):
>       a += 1
>     if other_calculation(params):
>       b += 1
>     return (a, b)
>
>   alpha = beta = 0
>   temp_a, temp_b = calculate(...)
>   alpha += temp_a
>   beta += temp_b
>
> Is there a better way to do this without holding each temporary
> result before using it to increment?
>

alpha = beta = 0
alpha, beta = (sum(x) for x in zip( (alpha, beta), calculate(...) ) )

It saves a couple lines of code, but at the expense of readability IMO.  If
I was reading the first, I'd know exactly what was happening immediately.
 If I was reading the second, it would take a bit to decipher.  In this
example, I don't see a better solution to what you're doing.

All the best,
Jason
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130607/7aa8d26d/attachment.html>


More information about the Python-list mailing list