Search notes:

Python: del

Removing a variable

del(var) removes a variable. After deleting it, the name of the variable is not known anymore. If such a deleted variable is then evaluated, a NameError exception is thrown.

Deleting elements in a list

del() can be used to remove elements from a list, thereby effectively shrinking size of the list by one element:
lst = [ 'zero', 'one', 'two', 'three', 'four']

print(len(lst))
#
#  5

del(lst[3])

print(len(lst))
#
#  4

print(' / '.join(lst))
#
#  zero / one / two / four
Github repository about-Python, path: /builtin-functions/del/list.py

Deleting keys from a dict

del() also removes elements from a dict. If the requsted key does not exist, del() throws a KeyError exception:
d = {}

d['one'         ] =  1
d['two'         ] =  2
d['three'       ] =  3
d['four'        ] =  4
d['ninety-nine' ] = 99


del d['three']

try:
   del d['XXXX']
except KeyError as e:
   print('Expected KeyError: {:s}'.format(str(e)))

for k, v in d.items():
   print('{:s} = {:d}'.format(k, v))
Github repository about-Python, path: /builtin-functions/del/dict.py

Calling __del__()

Because del(obj) removes the reference to the object that obj points to, the object's reference counter is decremented.
When the reference counter reaches zero, the object's __del()__ method is called.

See also

Python: Built in functions

Index