When is the `==` operator not equivalent to the `is` operator? (Python)

Not enough credits to upvote
3
Not enough credits to downvote
By: Speedbird (SysAdmin), Created 8 years ago, Updated 8 years ago.
I noticed I can use the == operator to compare all the native data types (integers, strings, booleans, floating point numbers etc) and also lists, tuples, sets and dictionaries which contain native data types. In these cases the == operator checks if two objects are equal. But in some other cases (trying to compare instances of classes I created) the == operator just checks if the two variables reference the same object (so in these cases the == operator is equivalent to the is operator)

My question is: When does the == operator do more than just comparing identities?
Tags

2 Responses

Not enough credits to upvote
13
Not enough credits to downvote
Accepted Answer
By: Branko (Member), 8 years ago
As Dag demonstrated, the ``is`` operator returns True only if two variables point to the same object. If you use the ``==`` operator, only values are compared. Thereforepyth:

>>> L1 = [1,2,3]
>>> L2 = [1,2,3]
>>> L1 == L2
True
>>> L1 is L2
False
>>> L1 = L2
>>> L1 is L2
True
>>>


For strings, though, you get different results:

>>> L1 = 'a'
>>> L2 = 'a'
>>> L1 == L2
True
>>> L1 is L2
True


The same applies to integers. So beware of this caveat. Strings and integers use the same reference if the values are the same, so they are always identical.

Not enough credits to upvote
4
Not enough credits to downvote
By: Dag (Member), 8 years ago
>>> L1 = [1,2,3]
>>> L2 = [1,2,3]
>>> L1 == L2
True
>>> L1 is L2
False

You may post an answer by signing in or registering for an account Here

QA-Stack.com

Welcome to QA-Stack.com - QA-Stack is a Q&A open source web application written in the best programming language in the galaxy: Python and using the best web framework in the solar system: web2py, be sure to check forum.qa-stack.com for discussions about this site. Have a great stay.

QA-Stack source code is available thanks to the cool folks at bitbucket.org, browse the source, or follow updates to this projects by visiting the qa-stack page at https://bitbucket.org/speedbird/qastack.

Documentation

Documentation for QA-Stack can be found at the QA-Stack Google Docs Page.

Bugs

Submit your bugs in i-track, another web application made by the same author (we eat our own dog food): View currently submitted bugs on i-track.

Popular Tags