Assign and increment value on one line
Not a pretty one but you can do something like this.
x = 1
a = x
x = b = x+1
x = c = x+1
>>> print a,b,c
>>> 1,2,3
>>>print id(a),id(b),id(c),id(x)
>>>31098952 31098928 31098904 31098904
Since Python 3.8, you can use the walrus operator which was introduced in PEP-572. This operator creates an assignment expression. So you can assign new values to variables, while returning the newly assigned value:
>>> print(f"{(x := 1)}")
1
>>> x
1
>>> print(f"{(x := x+1)}")
2
>>> x
2
>>> b = (x := x+1)
>>> b, x
(3, 3)
In the context of your question, this will work:
col = row = 1
ws.cell(row=row, column=col).value = "A cell value"
ws.cell(row=row, column=(col := col+1)).value = "Another cell value"
ws.cell(row=row, column=(col := col+1)).value = "Another cell value"
You can do it using a function,here I use the lambda function. There is no exact python equivalent of ++x
or x++
in c.
inc =lambda t: t+1
x = 1
a = x
b,x=inc(x),x+1
c,x = inc(x),x+1
print a
print b
print c
No that’s not possible in Python versions < 3.8.
Assignments (or augmented assignments) are statements and as such may not appear on the right-hand side of another assignment. You can only assign expressions to variables.
The reason for this is most likely to avoid confusions from side effects which are easily caused in other languages that support this.
However, normal assignments do support multiple targets, so you can assign the same expression to multiple variables. This of course still only allows you to have a single expression on the right-hand side (still no statement). In your case, since you want b
and x
to end up with the same value, you could write it like this:
b = x = x + 1
c = x = x + 1
Note that since you’re doing x = x + 1
you are no longer using an augmented assignment and as such could have different effects for some types (not for integers though).