Python del Operator (Remove at Index or Key)

Use del to remove one or more elements from a collection. Invoke del on lists and dictionaries.

Del built-in. This operator stands for "delete." The syntax for del is a bit unusual—it works more like the "in" operator than a method.In

With del, we specify a list, dictionary or other collection. We pass an index or key we want to remove. On lists, we can remove slices (ranges of elements) at once.

Del examples. Here we call del to remove the third element in a list. We compare this to the remove() method on list, which searches for the first matching value and then deletes it.List, strings
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]

Remove. This method is available on lists. It searches for the first element that has the specified value and removes it from the list.
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]

Syntax. Slice syntax is supported with the del built-in on a list. So we can remove a range of elements based on a slice. This is a good way to resize a list.Resize List
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']

Dictionary, del. We can use del on a dictionary. We pass the key we want to remove. It removes both the key and its associated value. Only one entry can be removed at a time.Dictionary
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}

Benchmark, del. This example benchmarks the del operator on a list against remove(). It is not perfect—the del code removes by index, but remove() searches by value.
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

String error. Del cannot be used on a string. It might make sense for it to remove characters, but this does not work. We use del on collections, not strings.
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

A summary. Del is a useful keyword. Its syntax may be confusing at first. But once we use del more like an operator, not a method call, it is easy to remember.

© 2007-2020 Sam Allen. Send bug reports to info@dotnetperls.com.