Clarify how python del works for lists and slices

前端 未结 2 1087
温柔的废话
温柔的废话 2021-01-21 14:33

Reading the docs:

del: Deletion of a target list recursively deletes each target, from left to right.

Can you clarify why this cod

2条回答
  •  面向向阳花
    2021-01-21 14:55

    Here’s what you’re doing:

    a = [1,2,3]
    

    Create new list object. Create name a pointing to it.

    c = a[:]
    

    Create copy of list object. Create name c pointing to it.

    del c
    

    Delete name c. The object it used to point to is now garbage and will be collected eventually. This has no effect on the first object.

    print a
    

    Print what a points to, the first object.

    del a[:]
    

    Delete all elements of the object that a points to. It is now an empty list.

    print a
    

    Print the empty list.

    So, what’s the difference between these lines?

    del c
    del a[:]
    

    The first line removes a name from the namespace. The second line removes elements from an object.

    Edit: I see, you’re not clear on why they act that way. From Python Language Reference, Section 6.5:

    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. If the name is unbound, a `NameError` exception will be raised.

    That’s what happens when you run del c.

    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).

    That’s what happens when you run del a[:].

提交回复
热议问题