What does i += x > 0 mean?

Viewed 78

I'm reviewing a block of code and I wonder what this expression means:

target += counter[s[left]] >= 0
2 Answers

counter[s[left]] >= 0 evaluates to a boolean, that is True or False.

Putting that aside, target += val is equivallent to target = target + val.

Since bool subclasses int, in a mathematical context True is 1 and False is 0.

In essence, this line (presumably inside a loop that modifies counter, s or left, or any combination of them) counts how many times counter[s[left]] is greater than or equal 0.

target += counter[s[left]] >= 0

is equivalent to

target = target + (1 if counter[s[left]] >= 0 else 0)

and it's bad Python. Demand it be changed. Adding zero is stupid, and the whole thing is confusing.

if counter[s[left]] >= 0:
    target += 1
Related