Incrementing a counter while assigning it in python

Python 3.8+ has the walrus operator, which allows you to assign to a variable within an expression. The expression var := expr assigns the value of expr to var, and results in that same value.

This means the pre-increment operator ++var can be simulated in Python by var := var + 1. This increments var and the result is the new, incremented value of var. This seems to be the behaviour you are looking for.

In languages which have these operators, the post-increment operator var++ has different behaviour; it increments var, but the value of the expression var++ is the old, un-incremented value of var. From your code sample, this doesn’t seem to be the behaviour you’re looking for, but for completeness, it can be simulated in Python by (var, var := var + 1)[0]. This evaluates to a tuple containing the old value of var and the new value of var after doing the increment, and then gets the first component of that tuple (i.e. the old, un-incremented value).

That said, I would recommend against using the former, and strongly recommend against the latter, since it’s highly non-idiomatic in Python. If you want to do two different things (i.e. increment num and format a string), it is more readable and understandable if you do them separately.

Leave a Comment