How to remove an item with the del statement in Python

When the Python coders work in the interactive console, or when they write scripts to be executed later in time, most of the time they make use of the del statement with the main purpose of removing an object. Beginners in the coding journey, need clear instructions so they can truly understand what a specific builtin utility achieves by being used in the Python computer programming language.

During this very short tutorial, codetheory will instruct the reader on the Python statement called del. According to the official documentation, the Python del statement can be used to remove entire variables. The syntax for it is being shown below.

del a

To illustrate the theory and put the Python del statement in a real world scenario, let’s create the following variable.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

name = ‘codetheory’

To get the value of the above variable, all one has to do, is to run the command shown below in their Python interactive shell.

name

Once the above Python command is executed in my Python interactive shell, I get the result shown below.

‘codetheory’

When the variable which we declared above is not needed anymore in our program, we can easily remove it with the help of the Python del statement.

del name

One can easily verify if the object has been deleted by the Python del statement or not, by trying to access it like shown below.

name

After running the above command, I got the error shown below. It proves that the Python del statement did what it is supposed to do.

Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘name’ is not defined

The Python coder can also delete elements from a list by using the del statement. A practical example is being shown below.

l = [1, 2, 3]
del l[0]

To check if the list has been updated or not, after the del statement operated on it, the following command can be used.

l

The result of the above Python command is being shown below.

[2, 3]

As you can see from the above result, the Python del statement acted similar to the specific list method pop. The difference is that unlike pop, the del statement did not return the element back to the caller.

Final thoughts

The Python del statement is very useful and practical when one wants to delete an object in their computer program.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Leave a Reply

Your email address will not be published. Required fields are marked *