4

Given the following code:

a = '1'
if a == 1:
    print 'yes'
else:
    print 'no'

we get output as no.

How is Python comparing a string value to an int here (if a == 1)? In C such a comparison would give an error because this is comparing different types.

0

1 Answer 1

6

Python is not C. Unlike C, Python supports equality testing between arbitrary types.

There is no 'how' here, strings don't support equality testing to integers, integers don't support equality testing to strings. So Python falls back to the default identity test behaviour, but the objects are not the same object, so the result is False.

See the Value comparisons section of the reference documentation:

The default behavior for equality comparison (== and !=) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e. x is y implies x == y).

If you wanted to compare integers to strings containing digits, then you need to convert the string to an integer or the integer so a string, then compare.

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

13 Comments

Out of curiosity, how does this square with other behaviors where there is type coercing: e.g. 3 is 3.0 == False but (3 == 3.0) == True (I'm not suggesting strings should be coerced, but I'm more asking about the final sentence in your quote.)
@brianpck: that's a chained comparison, which is the same thing as 3 is 3.0 and 3.0 == False. The first expression is not the same thing as the second.
@sanyesh: yes, when two names refer to the same object; in that case id(op1) will be the same as id(op2). It is the same test as op1 is op2.
@sanyesh: do check up on the documentation I already linked to: Sequences compare lexicographically using comparison of corresponding elements, whereby reflexivity of the elements is enforced. The lists are equal because their contents are equal.
@KarlKnechtel: nope, see the source code: strv.__eq__(intv) returns NotImplemented. It is the == operator implementation that then tries (intv).__eq__(strv) in the reverse operation, which also returns NotImplemented, before using identity equality.
|

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.