Idiomatic Python for incrementing pairs

Chris Angelico rosuav at gmail.com
Fri Jun 7 23:59:01 EDT 2013


On Sat, Jun 8, 2013 at 12:32 PM, Tim Chase
<python.list at tim.thechases.com> wrote:
>   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?

Can you pass the function a list with the appropriate values in them,
and have it return them via that?

  def calculate(params, sums):
    if some_calculation(params):
      sums[0] += 1
    if other_calculation(params):
      sums[1] += 1

  sums = [0, 0]
  calculate(..., sums)

Or use a dictionary if you'd rather they have names, either way.

ChrisA



More information about the Python-list mailing list