Different ways of deleting lists

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

    del a
    

    is removing the variable a from the scope. Quoting from python docs:

    Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block.

    del a[:]
    

    is simply removing the contents of a, since the deletion is passed to the a object, instead of applied to it. Again from the docs:

    Deletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object).

    .

提交回复
热议问题