1

Can someone explain why I am getting following outputs? (I know this code has SyntaxWarning.)

>>> a = 'book'
>>> a is 'book'
True
>>> a = 'two book'
>>> a is 'two book'
False

I was expecting same result for both code snippet.

m.r
  • 9
  • 3
  • Try : `a in 'two book'` – I'mahdi Mar 15 '23 at 20:11
  • why this code outputs True? :D – m.r Mar 15 '23 at 20:12
  • It has something to do with the internals of the Python runtime and might change between implementations and versions. Main point: Don't use `is` if you don't want to check for object identity. – Matthias Mar 15 '23 at 20:13
  • Using `is` with literals subjects you to any number of implementation-specific details. Basically, you can't say with any certainty what object a literal will produce. – chepner Mar 15 '23 at 20:14
  • The `SyntaxWarning` is obliquely telling you that the comparison produces [unspecified behavior](https://en.wikipedia.org/wiki/Unspecified_behavior). – chepner Mar 15 '23 at 20:16

1 Answers1

1

When comparing any 2 objects with "is" in python, you actually check the storage allocation of the 2 objects.

When creating a string, python tries to optimize the storage by using the same allocation for both. but this behavior isn't always consistent, for it might be different for other strings.

I notices this behavior changes when using a space (" ") as a part of the string.

Anyways, you should compare objects with "==" and not "is". This way, the comparison will use the "eq" method from the class of the object, as it should. Or you may implement this method by yourself if you'd like to (using inheritance and overriding)

Matan Bendak
  • 128
  • 6