2

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.

5
  • 5
    you can't with < or > but with "!=" or "==" it works. Not the same type => not equal Commented Oct 13, 2020 at 20:32
  • 2
    You can compare lists and ints for identity, but not value. This statement 3 != [3] is true, because they're different types. Commented Oct 13, 2020 at 20:33
  • 1
    note that different types can compare OK, example booleans & integers (because boolean is a specialized integer). Commented Oct 13, 2020 at 20:48
  • @Jean e.g. False == 0 == 0.0 Commented Oct 13, 2020 at 21:23
  • oh, right. Because equality operator has been redefined in that case. my answer is not exact. Commented Oct 13, 2020 at 21:36

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

"Objects of different types never compare equal", true but subject to interpretation. collections.defaultdict and dict can compare equal because one inherits from the other, but they're different types all right. That's not a critic of your answer, but rather of the documentation.
The == operator is always defined but for some object types (for example, class objects) is equivalent to is: unless redefined using __eq__ and __ne__

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.