C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: To use del on a list we must specify an index or a slice. We cannot use del to search for a value.
Note: Del is a clear and fast way to remove elements from a list. Often we can use it instead of the remove() method.
Python program that uses del
values = [100, 200, 300, 400, 500, 600]
# Use del to remove by an index or range of indexes.
del values[2]
print(values)
values = [100, 200, 300, 400, 500, 600]
# Use remove to remove by value.
values.remove(300)
print(values)
Output
[100, 200, 400, 500, 600]
[100, 200, 400, 500, 600]
Tip: The design of remove() involves a search. This makes it slower than del. A performance analysis is at the bottom.
Python program that uses list, remove
has_duplicates = [10, 20, 20, 20, 30]
# The remove method on list does not remove more than the first match.
has_duplicates.remove(20)
print(has_duplicates)
Output
[10, 20, 20, 30]
First argument: Before the ":" we specify the start index of the region we want to remove.
Second argument: This is the end index (not the count) of the target region. If no ":" is present, only one element is removed.
Python program that uses syntax
elements = ["A", "B", "C", "D"]
# Remove first element.
del elements[:1]
print(elements)
elements = ["A", "B", "C", "D"]
# Remove two middle elements.
del elements[1:3]
print(elements)
elements = ["A", "B", "C", "D"]
# Remove second element only.
del elements[1]
print(elements)
Output
['B', 'C', 'D']
['A', 'D']
['A', 'C', 'D']
Python program that uses dictionary, del
colors = {"red" : 100, "blue" : 50, "purple" : 75}
# Delete the pair with a key of "red."
del colors["red"]
print(colors)
Output
{'blue': 50, 'purple': 75}
Version 1: This version of the code uses the del operator to remove a certain value from a list.
Version 2: Here we call remove() instead of using del. This searches the list by value (unlike del).
Result: The del keyword is a faster way to remove an element than the remove method. It requires no searching.
Python program that times del, remove on list
import time
print(time.time())
# Version 1: use del on an index.
for i in range(0, 2000000):
values = [x for x in range(100)]
del values[95]
if len(values) != 99: break
print(time.time())
# Version 2: use list remove method on a value.
for i in range(0, 2000000):
values = [x for x in range(100)]
values.remove(95)
if len(values) != 99: break
print(time.time())
Output
1415214840.25
1415214841.46 1.21 s, del
1415214842.85 1.39 s, remove
Python program that causes del error
location = "beach"
# Cannot remove part of a string with del.
del location[1]
print(location)
Output
Traceback (most recent call last):
File "C:\programs\file.py", line 6, in <module>
del location[1]
TypeError: 'str' object doesn't support item deletion