Different ways of deleting lists

后端 未结 6 1079
攒了一身酷
攒了一身酷 2020-12-15 03:44

I want to understand why:

  • a = [];
  • del a; and
  • del a[:];

behave so differently.

I

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 04:11

    Test 1: rebinds a to a new object, b still holds a reference to the original object, a is just a name by rebinding a to a new object does not change the original object that b points to.

    Test 2: you del the name a so it no longer exists but again you still have a reference to the object in memory with b.

    Test 3 a[:] just like when you copy a list or want to change all the elements of a list refers to references to the objects stored in the list not the name a. b gets cleared also as again it is a reference to a so changes to the content of a will effect b.

    The behaviour is documented:

    There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example:

    >>>
    >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
    >>> del a[0]
    >>> a
    [1, 66.25, 333, 333, 1234.5]
    >>> del a[2:4]
    >>> a
    [1, 66.25, 1234.5]
    >>> del a[:]
    >>> a
    []
    

    del can also be used to delete entire variables:

    >>>
    >>> del a
    

    Referencing the name a hereafter is an error (at least until another value is assigned to it). We'll find other uses for del later.

    So only del a actually deletes a, a = [] rebinds a to a new object and del a[:] clears a. In your second test if b did not hold a reference to the object it would be garbage collected.

提交回复
热议问题