Object Identity in Strings

What is Object Identity?

Each object in Python has a unique identity, which can be seen using the built-in id() function. This identity is based on the memory location of the object. Python sometimes reuses objects for optimization, especially immutable ones like strings.

Examples

# Example 1: Two identical string literals share the same memory
a = "hello"
b = "hello"
print(id(a), id(b))       # Same id
print(a is b)             # True
# Example 2: Strings created differently may have different ids
x = "world"
y = "".join(["w", "o", "r", "l", "d"])
print(id(x), id(y))       # Likely different ids
print(x == y)             # True (same content)
print(x is y)             # False (different objects)
# Example 3: Reassigning changes identity
msg = "Hi"
print(id(msg))
msg = "Hello"
print(id(msg))            # Different id after reassignment
# Example 4: Small string interning in Python
a = "py"
b = "py"
print(a is b)             # True (interned)
print(id(a), id(b))
# Example 5: Comparing object ids
s1 = "example"
s2 = "example"
s3 = s1
print(s1 is s2)           # True (may be interned)
print(s1 is s3)           # True (same reference)