Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between 'is' and '==' [duplicate]

Tags:

python

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

like image 284
Robert Johnstone Avatar asked May 31 '12 11:05

Robert Johnstone


People also ask

Is duplicate means fake?

A “duplicate” refers to an exact copy of something. “Fake” refers to something being artificial or false. For example, if I print the same document twice, that's a duplicate; however, if I print the text of the constitution and say it's the original constitution, that's fake.

Is in duplicate meaning?

Definition of in duplicate 1 : so that there are two copies We were required to fill out the paperwork in duplicate. 2 : with an exact copy Please send the contract in duplicate.

Is reproduce the same as duplicate?

A duplicate is an exact copy. A reproduction is a close copy, and especially one made after the original is no longer available.

What is difference between duplicate and replicate?

Duplicate means to make an exact copy and can also be used as an adjective and a noun. Replicate means to reproduce something, and can also be used as an adjective and a noun.


2 Answers

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)

like image 146
Levon Avatar answered Oct 18 '22 04:10

Levon


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
like image 42
lvc Avatar answered Oct 18 '22 03:10

lvc