Discard a name
Remove a variable binding that should no longer be available in the current namespace.
Python · Const
del removes a name binding or deletes an item, attribute, or slice. It acts on targets and does not return a value.
The del statement removes bindings, items, attributes, or slices rather than producing a value. Its effect is delegated to the affected object for attributes and subscriptions, while deleting a name removes that name from the applicable namespace.
del target_listglobal declaration determines whether name deletion targets the global namespace.items = ["a", "b", "c", "d"]
del items[1:3]
print(items) # ['a', 'd']
name = "temporary"
del name
print("name" not in locals()) # TrueThe statement removes a list slice and then removes a local name.
Remove a variable binding that should no longer be available in the current namespace.
Remove one or more elements from a mutable sequence by index or slice.
Remove a mapping entry or object attribute through the target object's deletion protocol.
del?The syntax is del target_list. It can delete names, attributes, subscriptions, and slices; a target list is processed from left to right.
Follow-up: What happens with del x inside a function? The name is removed from the local namespace unless a global declaration makes it refer to the global namespace.
Deleting a name removes its binding from the local or global namespace. Attempting to delete a name that is not bound raises NameError.
Follow-up: Does deleting a name necessarily destroy its object? No; it removes one binding, while the object can remain reachable through other references.
del work with attributes, subscriptions, and slices?For an attribute or subscription, the operation is passed to the primary object, so the object's deletion behavior controls the result. Slice deletion is generally like assigning an empty slice of the appropriate type.
Follow-up: Why can slice deletion vary between objects? The documentation says the sliced object determines even the empty-slice behavior.
assignment statementglobal statementtarget listattribute referencessubscriptionsslicing