Chained And Condition Gives Ambiguous Result
Can someone explain the following? a = [2,3,4] b = [5,6,8,9] print(len(a) > 0) print(len(b) > 0) print((len(a) > 0) & len(b) > 0)) Output: True True False Should
Solution 1:
&
is not the logical "and" operator. It's the bitwise "and" operator, and as such, it has precedence suitable for a bitwise operation rather than a logical one. That precedence is higher than the precedence for comparison, so the expression is parsed as
((len(a) > 0) & len(b)) > 0
If you use a logical and
, the precedence works the way you expect:
print(len(a) > 0 and len(b) > 0)
Post a Comment for "Chained And Condition Gives Ambiguous Result"