== vs is. Differences between keyword 'is' and '=='. Comparisons in Python.
Python variable is bound to a memory address. And under a given memory address, we store an object.
The majority of newly created variables will receive a unique memory address but not all of them.
Some variables will be bound to the one memory address with exactly the same object.
After all, what is the point of keeping in memory more than one 313 number or more than one
"devcuriosity" string?
Python memory optimization is a complex algorithm. It is hard to list all rules standing behind
binding new variables to the existing memory addresses, but some of the general ideas would be:
- Object needs to be immutable
- Object needs to be a constant, known at the time Python parses the code.
This allows the interpreter to recognize and deduplicate identical immutable objects during execution.
- This optimization doesn't work in REPL (Python Standard Shell).
Python does that to optimize memory usage. Please keep in mind that there
are some exceptions to these rules as well. In general, it can be dangerous to build your logic around
those rules.