Different ways of deleting lists

后端 未结 6 1082
攒了一身酷
攒了一身酷 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:10

    To understand the difference between different ways of deleting lists, let us see each of them one by one with the help of images.

    >>> a1 = [1,2,3]
    

    A new list object is created and assigned to a1.

    i1

    >>> a2 = a1
    

    We assign a1 to a2. So, list a2 now points to the list object to which a1 points to.

    i2

    DIFFERENT METHODS EXPLAINED BELOW:

    Method-1 Using [] :

    >>> a1 = []
    

    i3

    On assigning an empty list to a1, there is no effect on a2. a2 still refers to the same list object but a1 now refers to an empty list.

    Method-2 Using del [:]

    >>> del a1[:]
    

    i4

    This deletes all the contents of the list object which a1 was pointing to. a1 now points to an empty list. Since a2 was also referring to the same list object, it also becomes an empty list.

    Method-3 Using del a1

    >>> del a1
    >>> a1
    NameError: name 'a1' is not defined
    

    i5

    This deletes the variable a1 from the scope. Here, just the variable a1 is removed, the original list is still present in the memory. a2 still points to that original list which a1 used to point to. If we now try to access a1, we will get a NameError.

提交回复
热议问题