Why is it not an error to compare a list to an integer?

Viewed 104

In the following example, print statement is evaluated with the output "test".

x = [3]
if x != 3:
    print("test")

But I don't understand how this works. Is the value x assigned to the address of the list [3] and therefore x != 3 evaluates to True? Because my intuition says that I should get an Error here since you can't compare a list to an int.

1 Answers

The Python documentation on Comparisons states in part:

Objects of different types, except different numeric types, never compare equal. The == operator is always defined but for some object types (for example, class objects) is equivalent to is. The <, <=, > and >= operators are only defined where they make sense; for example, they raise a TypeError exception when one of the arguments is a complex number.

Hence, Python will let you use == and != between any two types, but in the case of comparing a list to an integer, they will never compare equal.

Related