Different ways of deleting lists

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

    Of those three methods, only the third method actually results in deleting the list that 'a' points to. Lets do a quick overview.

    When you right a = [1, 2, 3] it creates a list in memory, with the items [1, 2, 3] and then gets 'a' to point to it. When you write b = a this preforms whats' called a 'shallow copy,' i.e. it makes 'b' point to the same block of memory as 'a.' a deep copy would involve copying the contents of the list into a new block of memory, then pointing to that.

    now, when you write a = [] you are creating a new list with no items in it, and getting 'a' to point to it. the original list still exists, and 'b' is pointing to it.

    in the second case, del a deletes the pointer to [1,2,3] and not the array it's self. this means b can still point to it.

    lastly, del a[:] goes through the data 'a' is pointing to and empties it's contents. 'a' still exists, so you can use it. 'b' also exists, but it points to the same empty list 'a' does, which is why it gives the same output.

提交回复
热议问题