Idiomatic Python for incrementing pairs

T

Tim Chase

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?

-tkc
 
S

Steven D'Aprano

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.
[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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,792
Messages
2,569,639
Members
45,353
Latest member
RogerDoger

Latest Threads

Top