Deniz Dogan Deniz Dogan - 1 year ago 87
Python Question

Python: Why does ("hello" is "hello") evaluate as True?

Why is

"hello" is "hello" == True
in Python?

I read the following here:

If two string literals are equal, they have been put to same
memory location. A string is an immutable entity. No harm can
be done.

So there is one and only one place in memory for every Python string? Sounds pretty strange. What's going on here?

Answer Source

Python (like Java, C, C++, .NET) uses string pooling / interning. The interpreter realises that "hello" is the same as "hello", so it optimizes and uses the same location in memory.

Another goodie: "hell" + "o" is "hello" ==> True

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download