[Tutor] is vs. ==

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 18 Apr 2002 20:54:43 -0700 (PDT)

On Thu, 18 Apr 2002, Ian! wrote:

> What's the difference between "is" and "=="? I always assumed they were
> the same.
> >>> __name__ == '__main__'
> 1
> >>> __name__ is '__main__'
> 0

Slightly different.

'==' can be thought of as "value equality", that is, if two things look
the same, == should return a true value.  (For those with a Java
background, Python's == is actually doing something akin to an equals()

'is' can be thought of as 'object identity', that is, if the two things
actually are the same object.

The concept is a little subtle, so let's use an example:

>>> my_name = "danny"
>>> your_name = "ian"
>>> my_name == your_name

My name and your name are different.  But what about this?

>>> my_name[1:3] == your_name[1:3]

Our names share something in common.  *grin* We'd say that my_name[1:3]
looks the same as your_name[1:3], so they're "equal" in some sense that's
captured by the idea of '=='.  However, the sources of those strings are
different, and we can see this when we check against object identity:

>>> my_name[1:3] is your_name[1:3]

'is' allows us to make the distinction if the system is keeping track of
two things that just look alike, or are actually the same thing.  Why this
is useful isn't too obvious for strings; it's more of an issue when one is
dealing with classes or mutable data structures like lists.

For now, you probably want to use '==' when you want to compare two things
for equality.  When you learn about data structures, then 'is' will seem
more relevant.

Please feel free to ask more questions!  Good luck.