Lists | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Lists

a =[1,2,3] b=a del a print(b) * output [1,2,3] If a and b references to the same object then if I am deleting a it means I am deleting the object(since del is used to del objects what I know) ,but why do I still have the b?

21st Nov 2021, 1:09 PM
Prabhas Koya
3 Answers
+ 5
The `del` command reduces the reference counter to a resource. Python keeps track how many objects are referencing the same resource. In your snippet both <a> and <b> references the same resource. When the reference counter reaches zero, it means there are no more object referencing the resource, and that garbage collection of the resource is considered safe. So in your snippet the resource reference counter was 2 initially. It was reduced to 1 as `del` was issued. But the resource isn't getting garbage collected, because Python sees that object <b> is still referencing the resource.
21st Nov 2021, 1:58 PM
Ipang
+ 4
I'm guessing that object <a> (which is referenced by <b>) is not yet getting garbage collected because its reference counter has not yet reached zero. Even though you explicitly deleted <a>, its reference counter isn't yet reaching zero because another object is still referencing the resource (object <b>). I could be wrong though, just a guess ...
21st Nov 2021, 1:35 PM
Ipang
+ 2
So what you mean is the del statement is used to delete the reference and not the object itself and unless there is only one reference it deletes both Obj and reference as counter reaches 0
21st Nov 2021, 1:43 PM
Prabhas Koya