0

I declared two variables as follows (one of which is the reverse of the other):

a = "test"
b = "tset" # reverse of a

I then ran this into the interpretor which returned the below value:

>>> b[::-1]
'test' # value returned

As you can see, it reversed the string which made it exactly like the first variable a. However, when I execute this statement, the results are not quite the same:

a is b[::-1]
False # returns false after executing above statement

a is "test", so is b[::-1]. So why is it that the condition does not evaluate to True?

Joseph Potts
  • 191
  • 2
  • 9

1 Answers1

2

To check for "values" equality you should use the operator ==:

>>> a == b[::-1]
True

So why is it that the condition does not evaluate to True?

The is keyword is used to compare objects identity; in other words, if the objects are the same.

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
  • Are they not? They're both of type string and have the same value. – Joseph Potts Mar 25 '14 at 20:32
  • 1
    @JosephPotts: if I have a quarter, and you have a quarter, the quarters may be equal (`==`), but they're not necessarily the same quarter (`is`) even though they're both of type coin and have the same value. They could be, if someone happens to leave us the same quarter in her will, but they needn't be. – DSM Mar 25 '14 at 20:33
  • 1
    @JosephPotts if you want a detailed-explanation, you can read [this answer](http://stackoverflow.com/questions/15541404/python-string-interning). – Christian Tapia Mar 25 '14 at 20:34