difference between 'is' and '=='

python

Solution

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)

Problem

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

Original source

Related problems