5

Is it possible to do multiple variable increments on the same line in Python?

Example:

value1, value2, value3 = 0
value4 = 100
value1, value2, value3 += value4

In my real program I have LOTS of variables that are different but must all be added on with a single variable at one point.

What I am currently doing that I wanted this to replace:

value1 += value4
value2 += value4
value3 += value4
...
value25 += value4
2
  • Why don't u use list instead or dict? Commented Jan 9, 2016 at 13:21
  • 4
    value1, value2, value3 = (v + value4 for v in (value1, value2, value3))... Commented Jan 9, 2016 at 13:22

4 Answers 4

8

Tuple and generator unpacking can be useful here:

value1, value2, value3 = 0, 0, 0
value4 = 100
value1, value2, value3 = (value4 + x for x in (value1, value2, value3))
Sign up to request clarification or add additional context in comments.

2 Comments

@MikeMüller, that's not tuple unpacking, that's iterable unpacking of a generator expression.
@MikeGraham Thanks for the pointer. My wording is not totally correct. In the last line no tuple is created. Fixed. I used tuple unpacking for the more general iterable unpacking.
4

You can create special function for it:

def inc(value, *args):
    for i in args:
        yield i+value

And use it:

value1 = value2 = value3 = 0
value4 = 100
value1, value2, value3 = inc(value4, value1, value2, value3)

1 Comment

This is an interesting way to do it, however still very long to type.
1

You can update the variables through the dictionary of the current namespace (e.g. vars()):

>>> value1 = value2 = value3 = 0
>>> value4 = 100
>>> for varname in ("value1", "value2", "value3"):
...     vars()[varname] += value4
... 
>>> value1, value2, value3
(100, 100, 100)

Comments

-5

There is an easy way by making a list and looping over it:

value1, value2, value3 = 0
value4 = 100
valuelist = [value1, value2, value3]
for x in valuelist:
    x += value4

3 Comments

That doesn't work -- ints are immutable, += rebinds the name, not mutates the value
@MikeGraham Then what would be mutable? Maybe converting value1-3 to these mutable values inside the list may work.
the solution is just not to try to use mutation here, but rather create and assign new values. stackoverflow.com/a/34694027/192839 was a pretty reasonable solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.