Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
in Python by (3.9k points)
edited by

I've set two variables to the value 'qwerty' in Python. In a conditional expression 

which fails i.e. var1 is var2 , but when I use var1 == var2 and the output comes True.

But in my Python interpreter the same succeeds:

    >>> s5 = 'public'
    >>> s6 = 'public'
    >>> s5 is s6

Can someone tell me what mistakes I am doing?

2 Answers

0 votes
by (46k points)
edited by

== compares the values whereas is tests for object identity.

check this for ref.

>>> a = 'qwe'
>>> b = ''.join(['q', 'w', 'e'])
>>> q == e
>>> q is e

0 votes
by (106k points)
edited by

The is keyword tests the identity, while ‘ == ‘ is for equality testing. 

Your code would be emulated in the interpreter like following:

a = 'abc' 

b = ''.join(['a', 'b', 'c']) 

a == b

a is b 

We can see that they are not the same. In other words, the ‘is’ keyword returns true or false if id of (a) == id of (b).

You can use the following video tutorials to clear all your doubts:-

Browse Categories