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
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))