del
In Python, the del
keyword deletes names from a given scope or namespace. This includes variables, list items, and dictionary keys, among other objects. It helps you manage memory by freeing up space taken by unnecessary objects.
Python del
Keyword Examples
Here’s a quick example showing how to use del
to remove an item from a list:
>>> numbers = [1, 2, 3, 4, 5]
>>> del numbers[2]
>>> numbers
[1, 2, 4, 5]
In this example, the del
keyword removes the item at index 2
from numbers
, which is the number 3
. After the deletion, numbers
contains the elements [1, 2, 4, 5]
.
You can also use del
to delete variables:
>>> x = 10
>>> del x
>>> x
Traceback (most recent call last):
...
NameError: name 'x' is not defined
In this case, del
removes the variable x
, and trying to access x
afterward raises a NameError
exception.
Python del
Keyword Use Cases
- Remove specific items from a list or entire lists
- Delete dictionary entries or entire dictionaries
- Free up memory by deleting variables that are no longer needed
Related Resources
Tutorial
Python's del: Remove References From Scopes and Containers
In this tutorial, you'll learn how Python's del statement works and how to use it in your code. This statement will allow you to remove references from different scopes, items from lists, keys from dictionaries, and members from classes. This will lead to potentially memory-efficient code.
For additional information on related topics, take a look at the following resources: