Idiomatic Python for incrementing pairs

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jun 8 02:39:46 EDT 2013


On Fri, 07 Jun 2013 21:32:39 -0500, Tim Chase 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
[...skip misleading and irrelevant calculate() function...]

>   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?

Not really. The above idiom is not really terribly Pythonic. It's more 
like the sort of old-fashioned procedural code I'd write in Pascal or 
COBOL or similar.

For just two variables, it's not so bad, although I'd probably save a 
line and a temporary variable and write it as this:

alpha = beta = 0
tmp = calculate(...)
alpha, beta = alpha+tmp[0], beta+tmp[1]


But if you have many such values, that's a sign that you're doing it 
wrong. Do it like this instead:

values = [0]*17  # or however many variables you have
increments = calculate(...)
values = [a+b for a,b in zip(values, increments)]


Or define a helper function:

add(v1, v2):
    """Vector addition.

    >>> add([1, 2], [4, 5])
    [5, 7]

    """
    return [a+b for a,b in zip(v1, v2)]


values = [0]*17
increments = calculate(...)
values = add(values, increments)


Much nicer!

And finally, if speed is absolutely critical, this scales to using fast 
vector libraries like numpy. Just use numpy arrays instead of lists, and 
+ instead of the add helper function, and Bob's yer uncle.


-- 
Steven



More information about the Python-list mailing list