Skip to content Skip to sidebar Skip to footer

Incrementing A Counter While Assigning It In Python

Is it possible to do the following in python somehow? nodename = 'node%s' % (++num if ct[0] != 'J' else num) Or do I need to first do the increment and the assign it on the next l

Solution 1:

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 operatorvar++ 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.

Post a Comment for "Incrementing A Counter While Assigning It In Python"