Multiple increment operators on the same line Python
Asked Answered
B

4

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
Bhutan answered 9/1, 2016 at 13:17 Comment(2)
Why don't u use list instead or dict?Kosygin
value1, value2, value3 = (v + value4 for v in (value1, value2, value3))...Moina
S
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)
Servant answered 9/1, 2016 at 13:41 Comment(1)
This is an interesting way to do it, however still very long to type.Bhutan
K
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))
Kaciekacy answered 9/1, 2016 at 13:27 Comment(2)
@MikeMüller, that's not tuple unpacking, that's iterable unpacking of a generator expression.Countercharge
@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.Nathalie
S
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)
Servant answered 9/1, 2016 at 13:41 Comment(1)
This is an interesting way to do it, however still very long to type.Bhutan
E
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)
Execute answered 9/1, 2016 at 20:24 Comment(0)
L
-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
Lolalolande answered 9/1, 2016 at 13:44 Comment(3)
That doesn't work -- ints are immutable, += rebinds the name, not mutates the valueCountercharge
@MikeGraham Then what would be mutable? Maybe converting value1-3 to these mutable values inside the list may work.Lolalolande
the solution is just not to try to use mutation here, but rather create and assign new values. https://mcmap.net/q/1984073/-multiple-increment-operators-on-the-same-line-python was a pretty reasonable solutionCountercharge

© 2022 - 2024 — McMap. All rights reserved.