How to use the del function in Python

In Python, ‘del’ is a keyword used for deleting objects or elements of objects. It has several common usages:

  1. remove
    x = 10
    del x  # 删除变量x
    
    1. delete element at index in list
    my_list = [1, 2, 3, 4, 5]
    del my_list[2]  # 删除索引为2的元素,即删除列表中的数字3
    
    1. delete []
    my_dict = {'a': 1, 'b': 2, 'c': 3}
    del my_dict['b']  # 删除键为'b'的键值对,即删除字典中的键'b'
    
    1. delete the .
      class MyClass:
          def __init__(self):
              self.x = 10
              self.y = 20
      
      obj = MyClass()
      del obj.x  # 删除对象obj的属性x
      

      It is important to note that ‘del’ only deletes the reference to an object, it does not delete the object itself. The object will be garbage collected when there are no references to it, freeing up memory space.