0

I have a query,

X="hello"
Y="hello"

X is Y giving true but

X="hel lo"
Y="hel lo"

X is Y giving false

Why?

Denziloe
  • 7,473
  • 3
  • 24
  • 34
  • 1
    Try x==y instead. "is" tests for identity, not equality. So it compares the memory adresses. – Florian H Sep 03 '18 at 13:59
  • 1
    Certain strings in Python are interned. – heemayl Sep 03 '18 at 14:00
  • I'm not sure that the duplicates clearly answer the question, which is different in that the literals are the same and created in exactly the same way. It's not obvious here why the strings are interned in one case but not the other. – Denziloe Sep 03 '18 at 14:03
  • 1
    @Denziloe There's a paragraph or two about strings having to be valid python identifiers in order to be interned. – Aran-Fey Sep 03 '18 at 14:08
  • @Aran-Fey Thanks. I think it would be best to link directly to that answer, because it's the only one of relevance: https://stackoverflow.com/a/24245514/5506894 – Denziloe Sep 03 '18 at 14:10
  • In the case of X="hello" Y="hello", Python interns the string "hello", which means storage is created only once for "hello". X and Y will have the same memory location - you can find this using the id function. When X = "hel lo" and Y = "hel lo", Python is not doing the interning. This is the reason you are getting false for X is Y. Choice of interning a string is left to the specific Python implementation – Ravi S Sep 03 '18 at 14:36

0 Answers0