0

In Python 3, passing a reference to an object in name space to del does not work when wrapped in a list.

a = 'foo'

for x in [a]:
    del(x)
print(a)

del(a)
print(a)

The first call to del silently does nothing, only the second one deletes a. Why does this happen, and how would I pass references in a list to del to delete the reference (in this case a)?

  • My best guess is that `del` deletes the reference in the list. Still, how would I need to construct the list so that it contains a reference to `a` so it get's deleted from name space? – Felix Binder Dec 27 '20 at 02:24
  • The first code deletes the iterator, not the actual strings – U13-Forward Dec 27 '20 at 02:25
  • 1
    Objects don't know what names point to them. So trying to deleting a name from an object reference is doomed. Thankfully, you never need to do this. If you need to associated a name with an object, you can use a dictionary. – Mark Dec 27 '20 at 02:29
  • Does [this](https://stackoverflow.com/questions/3013304/how-to-delete-every-reference-of-an-object-in-python) answer the question? – Noah Dec 27 '20 at 02:30

0 Answers0