2

Just started with Python (2.0, if that matters), and this is purely for the sake of curiosity, but I was wondering exactly what was going behind the scenes in the following scenario using "==" and "is":

a = 'cats'
a == 'cats'
True
a is 'cats'
True

a = 'cats!'
a == 'cats!'
True
a is 'cats!'
False

Somehow, the inclusion of punctuation is preventing a match by identity using is (which makes sense, since it's a string and not an integer value), but why does the first example ('cats' with no !) evaluate to true?

I thought I had a handle on the difference between "==" and "is" and what it meant to check equality and identity, but this making me question, well... everything.

davidism
  • 121,510
  • 29
  • 395
  • 339
Adam Templeton
  • 4,467
  • 7
  • 27
  • 39
  • `cats` happens to be a valid Python identifier too, is why. – Martijn Pieters Sep 03 '15 at 17:44
  • And the universe makes sense again! Thanks. – Adam Templeton Sep 03 '15 at 17:50
  • I didn't say `cats` is a keyword (a reserved term, like `if` or `while`), just that it could be used as a variable name. Python stores all your variables in Python dictionaries and other structures and thus uses Python strings a lot and interning strings that look like valid identifiers pays of. `cats!` is not a valid identifier and doesn't get the same treatment. – Martijn Pieters Sep 03 '15 at 19:38
  • Oh, okay. I think I understand what you're saying. Because "cats" could conceivably be a key name in a Python dictionary, it has properties that that "cats!" does not (which is why "cats_" is recognized by "is," but "cats/" is not). – Adam Templeton Sep 03 '15 at 20:20

0 Answers0