Deleting with `del`
Life with Python #5
So today I learned about del in python. It is a keyword that has the simplest of functionalities, namely that it will delete objects. Deletable objects could be a variable, list item, dictionary entry, or even an entire list or dictionary.
Get Prathik C’s stories in your inbox
Join Medium for free to get updates from this writer.
The basic syntax for using del is:
del <whatever_is_to_be_deleted>, <whatever_else_is_to_be_deleted>, ...Now let’s take a closer look at the different contexts for using del, shall we?
- Deleting Variables/Objects
When you usedelon a variable/object, it removes the reference to that in memory. Basically, it will no longer be accessible in any way in the program, as if it never existed in the first place.
x = "whatever you want"
del x
print(x) # Raises a NameError because x no longer exists
set_1 = {1,2,3}
del set_1
set_1.add(4) # we get a NameErrorWe can also have multiple variables/objects deleted in the same line by separating them with a comma. For example:
b = 'bee'
a = 10
z = {1:34,3:14}
del a, b, z
print(a) # NameError is raised as a no longer exists
print(b) # NameError again
print(z) # NameError againEntire objects can be deleted such as sets, dictionaries, lists, any user-defined class objects etc.
- Deleting List Items and List Slices
You can delete specific items from a list by specifying the index. You can also delete slices from lists as well. Consider the following example:
numbers = [1, 2, 3, 4, 5]
del numbers[2]
print(numbers) # Output: [1, 2, 4, 5]
del numbers[1:3]
print(numbers) # Output: [1, 5]- Deleting Dictionary Entries
To delete a key-value pair in a dictionary, you can usedelwith the key as shown below.
person = {"name": "Alice", "age": 25}
del person["age"] # CANNOT use del person.get("age")
print(person) # Output: {"name": "Alice"}That’s it from me for this time. del and out! :D Until next time!







