6

Possible Duplicate:
Is there any difference between “foo is None” and “foo == None”?

Quite a simple question really.

Whats the difference between:

if a.b is 'something':

and

if a.b == 'something':

excuse my ignorance

Community
  • 1
  • 1
Robert Johnstone
  • 5,431
  • 12
  • 58
  • 88

2 Answers2

5

The first checks for identity the second for equality.

Examples:

The first operation using is may or may not result in True based on where these items, i.e., strings, are stored in memory.

a='this is a very long string'
b='this is a very long string'

a is b
False

Checking, id() shows them stored at different locations.

id(a)
62751232

id(b)
62664432

The second operation (==) will give True since the strings are equal.

a == b
True

Another example showing that is can be True or False (compare with the first example), but == works the way we'd expect:

'3' is '3'
True

this implies that both of these short literals were stored in the same memory location unlike the two longer strings in the example above.

'3' == '3'
True

No surprise here, what we would have expected.

I believe is uses id() to determine if the same objects in memory are referred to (see @SvenMarnach comment below for more details)

Levon
  • 138,105
  • 33
  • 200
  • 191
  • "I believe is uses id() to determine if the same objects in memory are referred to." Not exactly -- `is` simply compares the pointers. In the CPython implementation, `id()` returns the pointer as an integer, so this will be equivalent. – Sven Marnach May 31 '12 at 11:18
  • @SvenMarnach Thanks Sven, I'll update my answer to point to your comment. – Levon May 31 '12 at 11:20
  • I've only ever used `is` in `if a.b is None` context. Any other example of when you could use it (e.g. would you use it to compare object instances?) – Robert Johnstone May 31 '12 at 12:00
  • Sorry I got my answer from the duplicate :) – Robert Johnstone May 31 '12 at 12:02
3

a is b is true if a and b are the same object. They can compare equal, but be different objects, eg:

>>> a = [1, 2]
>>> b = [1, 2]
>>> c = b
>>> a is b
False
>>> a is c
False
>>> b is c
True
>>> a == b == c
True
lvc
  • 34,233
  • 10
  • 73
  • 98