As I understand it, when creating a variable, we are creating an object, and the name of the variable refers to it.
If I do:
a = 2
a = "Hola"
The garbage collector takes care of deleting object 2, since it doesn't need it and no other variable is referencing it in the program. Instead if I write:
a = 2
b = a
a = "Hola"
Since b is referencing object 2, I now have both objects in memory, and neither is deleted.
I am right? Thank you very much.
A piece of advice: in python don't think of objects that are created or destroyed, rather think of objects that you access through their name, a mere label with which you tell the interpreter what to do.
Anything you see about "variable creation" or "variable assignment" is legacy from how it was thought of in other languages. Names are "given" in python .
To follow your example:
We identify the integer type object with the name . Then, we identify the string object with the name . The only thing you can ensure now is that the name identifies the string ; you cannot know what has happened to the object . It is possible that it was referencing with another name and that it cannot be deleted. It is also possible that, being such a common object, it is always available in memory. In python, all numbers from -5 to 256 exist in memory, even if nobody uses them, for optimization purposes.
2
a
"Hola"
a
a
"Hola"
2
One way to confirm:
id()
returns a unique identifier for each object. If two objects have the same identifier, they are the same object.Something more curious happens with the strings:
This behavior corresponds to an automatic "string internalization" process used in interpreter optimizations. This process caches all the character strings present in the code that comply with the variable naming rules. In the previous case, it
hola2
could serve as the name of a variable,hola 2
no. Any internalized string will never be deleted , even if it is not referenced.To conclude, let's look at the last case:
Here, what is done is to give another name,
b
to the object that pointed toa
. Nothing is created, nothing is destroyed.Entering at a lower level, it is not the GC that destroys the objects. Objects have a reference count so when this count reaches zero, they self-destruct.
The GC is an instrument that the interpreter has to free memory in certain cases that are complex to detect, such as circular references :
Here we have created two lists that are self-referencing and then we have deleted our references. Although we no longer have a way to access these lists, they are referencing each other, so their reference counters never reach zero. It has to be the GC who is in charge of checking that there is no other object that needs them and eliminates them from memory.
your first example:
your second example
answering your question: you have two variables a, b because they have different names.