Is there something similar to if (--arr[i] < 0) in Python?

Viewed 35

Didn't find a similar question. Say I have an array count, in C++ I can write an if statement like

if (--count[i] < 0) {
    return -1;
}

but in Python I have to do

if count[i] - 1 < 0:
    count[i] -= 1
    return -1

Just wonder if there is a better way or more concise way to write this python code. Thanks!

1 Answers

You can use the walrus operator to perform an assignment in an expression

if (count[i] := count[i] - 1) < 0:
    return -1

Note that this is only equivalent for pre-increment. To get the equivalent of a post-increment test, you'd have to write this mouthful:

if [count[i], count[i] := count[i] - 1][0] < 0:
Related