Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign and increment value on one line

Tags:

python

Is it possible to assign a value and increment the assigned value on the same line in Python?

Something like this:

x = 1
a = x
b = (x += 1)
c = (x += 1)

print a
print b
print c

>>> 1
>>> 2
>>> 3

I need it in a context where I'm creating an Excel sheet:

col = row = 1
ws.cell(row=row, column=col).value = "A cell value"
ws.cell(row=row, column=(col += 1)).value = "Another cell value"
ws.cell(row=row, column=(col += 1)).value = "Another cell value"
like image 632
Vingtoft Avatar asked Jan 09 '16 13:01

Vingtoft


2 Answers

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

like image 118
poke Avatar answered Sep 25 '22 19:09

poke


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"
like image 28
Tomerikoo Avatar answered Sep 26 '22 19:09

Tomerikoo