The del command

suggest change

This command has several related yet distinct forms.

del v

If v is a variable, the command del v removes the variable from its scope. For example:

x = 5
print(x) # out: 5
del x
print(x) # NameError: name 'f' is not defined
Note that del is a binding occurence, which means that unless explicitly stated otherwise (using nonlocal or global), del v will make v local to the current scope. If you intend to delete v in an outer scope, use nonlocal v or global v in the same scope of the del v statement.

In all the following, the intention of a command is a default behavior but is not enforced by the language. A class might be written in a way that invalidates this intention.

del v.name

This command triggers a call to v.__delattr__(name).

The intention is to make the attribute name unavailable. For example:

class A:
    pass

a = A()
a.x = 7
print(a.x) # out: 7
del a.x
print(a.x) # error: AttributeError: 'A' object has no attribute 'x'

del v[item]

This command triggers a call to v.__delitem__(item).

The intention is that item will not belong in the mapping implemented by the object v. For example:

x = {'a': 1, 'b': 2}
del x['a']
print(x) #  out: {'b': 2}
print(x['a']) # error: KeyError: 'a'

del v[a:b]

This actually calls v.__delslice__(a, b).

The intention is similar to the one described above, but with slices - ranges of items instead of a single item. For example:

x = [0, 1, 2, 3, 4]
del x[1:3]
print(x) #  out: [0, 3, 4]

See also Garbage Collection#The del command.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Variable Scope and Binding:
* The del command

Table Of Contents
2 Filter
3 List
7 Loops
13 Variable Scope and Binding
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve