Operators ‘==’ and ‘is’ in Python

There is a quite big difference between ‘==’ and ‘is’ operators in Python. The following example will show that:

>>> a = [1, 2]

>>> b = [1, 2]

>>> p = ‘str’

>>> q = ‘str’

>>> a == b

True

>>> p == q

True

>>> p is q

True

>>> a is b

False

If ‘p is q’ is True, the why not ‘a is b’? Both ‘a’ and ‘b’ have the same content, but ‘a’ is not ‘b’. But for the same in ‘p’ and ‘q’ its True. The reason is simple, the ‘==’ operator just check whether the contents of the operands are same. Hence ‘==’ give the result True in both cases. The ‘is’ operator checks whether both the operands share the same memory location.

But still there is a confusion about sharing memory by ‘a’ and ‘b’ or ‘p’ and ‘q’. The answer is quite simple. ‘a’ and ‘b’ holds a mutable object(list) but ‘p’ and ‘q’ holds an immutable object(string). Since strings are immutable there is no need of storing them at different locations. All the variables holding the same string can have a single memory reference value pointing to a location of ‘str’. This cannot be done for mutable objects, because the mutable objects can be changed by anyone at any time.

Advertisements

About Odol Shinu

I've completed my B Tech in Information Technology in 2010 from Government Engineering College Sreekrishnapuram Palakkad under Calicut University.

Posted on September 2, 2010, in Python. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: