Coming from Java, I have trouble understanding how objects are allocated in Python.
Consider this Python script:
x = ("a", "b")
y = ("a", "b")
print(x is y) # True
x = ["a", "b"]
y = ["a", "b"]
print(x is y) # False
In languages similar to Java, new keyword assures that a new instance with another memory location is created.
But I’m assuming that’s not the case here. So how can this behavior be explained? Is there any kind of pool for immutable types in Python to prevent duplicate literals?
I guess that Python keeps track of immutable types since the same case returns True for strings, complex numbers and other immutable objects. But if so, why bother?
Mohammad Javad is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Is there any kind of pool for immutable types in Python to prevent duplicate literals?
Essentially yes.