Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python object deletion

a = [1,2,3,4,5]
b = a[1]
print id(a[1],b)   # out put shows same id.hence both represent same object.
del a[1]           # deleting a[1],both a[1],b have same id,hence both are aliases
print a            # output: [1,3,4,5]
print b            # output: 2

Both b,a[1] have same id but deleting one isn't effecting the other.Python reference states that 'del' on a subscription deletes the actual object,not the name object binding. Output: [1,3,4,5] proves this statement.But how is it possible that 'b' remains unaffected when both a[0] and b have same id.

Edit: The part 'del' on a subscription deletes the actual object,not the name object binding is not true.The reverse is true. 'del' actually removes the name,object bindings.In case of 'del' on subscription (eg. del a[1]) removes object 2 from the list object and also removes the current a[1] binding to 2 and makes a[1] bind to 3 instead. Subsequent indexes follow the pattern.

like image 838
tez Avatar asked Dec 06 '22 11:12

tez


1 Answers

del doesn't delete objects, it deletes references.

There is an object which is the integer value 2. That one single object was referred to by two places; a[1] and b.

You deleted a[1], so that reference was gone. But that has no effect on the object 2, only on the reference that was in a[1]. So the reference accessible through the name b still reaches the object 2 just fine.

Even if you del all the references, that has no effect on the object. Python is a garbage collected language, so it is responsible for noticing when an object is no longer referenced anywhere at all, so that it can reclaim the memory occupied by the object. That will happen some time after the object is no longer reachable.1


1 CPython uses reference counting to implement it's garbage collection2, which allows us to say that objects will usually be reclaimed as soon as their last reference dies, but that's an implementation detail not part of the language specification. You don't have to understand exactly how Python collects its garbage and shouldn't write programs that depend on it; other Python implementations such as Jython, PyPy, and IronPython do not implement garbage collection this way.

2 Plus an additional garbage collection mechanism to detect cyclic garbage, which reference counting can't handle.

like image 134
Ben Avatar answered Dec 15 '22 02:12

Ben