DEV Community

Mr #1738
Mr #1738

Posted on

Removing Values from Lists with del Statements in python.

The del statement will delete values at an index in a list.All of the values in the list after the deleted value will be moved up one index. For example,enter the following into the interactive shell:

>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat']
Enter fullscreen mode Exit fullscreen mode

The del statement can also be used on a simple variable to delete it, as if it were an “unassignment” statement. If you try to use the variable after deleting it, you will get a NameError error because the variable no longer exists.
In practice, you almost never need to delete simplevariables. The del statement is mostly used to delete values from list.

Top comments (0)