del Operator

Python's del operator is used to delete an object. It can be used to delete a variable, a list, or a part of a list (slice).

Deleting a Variable

We've already seen how to declare a variable.

Filename: del.py

a = 10
print(a)

This outputs a number:

10

Actually, we can delete the variable a using the del operator.

del a

Deletion is the opossite of declaration. The variable a does not exist anymore! So, if we try to print it:

print(a)

System will throw an error:

Traceback (most recent call last):
  File "del.py", line 11, in <module>
    print(a)
          ^
NameError: name 'a' is not defined

Delete an Item from a List

You can use del to delete an item from a list. This looks pretty much like pop() method which we discussed in the previous section, but del does not return the deleted item.

Filename: del_list.py

names = ['Guido', 'Jukka', 'Ivan', 'Tim', 'Raymond']
del names[1]  # remove 'Jukka'
print(names)

This outputs:

['Guido', 'Ivan', 'Tim', 'Raymond']

Delete a Slice from a List

del can also be used to delete a slice from a list. This makes del more powerful than pop() method.

Here's an example:

del names[1:3]  # remove 'Ivan' and 'Tim'
print(names)

which gives:

['Guido', 'Raymond']