Python del statement

The del statement doesn’t reclaim memory. It removes a reference, which decrements the reference count on the value. If the count is zero, the memory can be reclaimed. CPython will reclaim the memory immediately, there’s no need to wait for the garbage collector to run. In fact, the garbage collector is only needed for reclaiming … Read more

Delete all objects in a list

tl;dr; mylist.clear() # Added in Python 3.3 del mylist[:] are probably the best ways to do this. The rest of this answer tries to explain why some of your other efforts didn’t work. cpython at least works on reference counting to determine when objects will be deleted. Here you have multiple references to the same … Read more

Which is better in python, del or delattr?

The first is more efficient than the second. del foo.bar compiles to two bytecode instructions: 2 0 LOAD_FAST 0 (foo) 3 DELETE_ATTR 0 (bar) whereas delattr(foo, “bar”) takes five: 2 0 LOAD_GLOBAL 0 (delattr) 3 LOAD_FAST 0 (foo) 6 LOAD_CONST 1 (‘bar’) 9 CALL_FUNCTION 2 12 POP_TOP This translates into the first running slightly faster … Read more

Delete an element from a dictionary

The del statement removes an element: del d[key] Note that this mutates the existing dictionary, so the contents of the dictionary changes for anybody else who has a reference to the same instance. To return a new dictionary, make a copy of the dictionary: def removekey(d, key): r = dict(d) del r[key] return r The … Read more