VFLOYD
VFLOYD

Reputation: 11

Why do I get different results with the same code in Python?

L = [1,2,3]

print(len(L) == 3 & len(L) > 2)
print(len(L) > 2 & len(L) == 3)

^^ the top one evaluates to true and the bottom one evaluates to false? Why? Aren't they the same thing?

Upvotes: 1

Views: 35

Answers (2)

Karl Knechtel
Karl Knechtel

Reputation: 61643

To explain in more detail: & performs a bitwise comparison, but it also has higher precedence than the relational operators (unlike the logical and).

len(L) == 3 & len(L) > 2

This compares len(L) == (3 & len(L)) as well as (3 & len(L)) > 2 (chained relational operators - the 3 & len(L) is only evaluated once). Since len(L) is equal to 3, 3 & len(L) evaluates to 3 as well (bitwise AND). 3 == 3 and 3 > 2, so this is true.

len(L) > 2 & len(L) == 3

Similarly: 2 & len(L) evaluates to 2. 2 > 2 is false (and for good measure, 2 == 3 is also false), so this evaluates false.

Upvotes: 4

Sam
Sam

Reputation: 1415

You don't want to use & for the logical AND operator, use the word and:

>>> L = [1,2,3]
>>> print(len(L) == 3 and len(L) > 2)
>>> print(len(L) > 2 and len(L) == 3)
True
True

Upvotes: 1

Related Questions