Python Ternary Operator And Assignment In Else
Ternary operator is very useful, why it does not work in this particular case: c='d' d={} d[c]+=1 if c in d else d[c]=1 It gives: d[c]+=1 if c in d else d[c]=1
Solution 1:
The ternary operator works on expressions, not statements. Assignment is a statement. Use a regular if
/else
.
Solution 2:
The correct way to write this would be:
d[c] = (d[c] + 1) if c in d else 1
Post a Comment for "Python Ternary Operator And Assignment In Else"