I am trying to delete a list within a list but my code is unable to do so even though I have deleted the list.
y = [45]
x = [1,2,3,5,y]
del y
print(x)
Output of printing x:
[1, 2, 3, 5, [45]]
My output shows as [1, 2, 3, 5, [45]] which means list y still exists in list x.
But I deleted list y in my code. Why is list y still not deleted then? Is there something wrong with my code? How do I delete an entire list in Python?
deldeletes references, not objects. In your case you have to use the.remove()method of the listxand remove all other references to the list, then the list will eventually be garbage collected.yis put intox, the value ofyis retrieved, not a weak reference. This means that though they are the same list, deletingywill not remove it from all the places it's used in. If you want, check out theweakrefmodule. If you wanted to clear the list, uselist.clear.