A Python list is a collection of objects that are indexed, ordered, and mutable.
There are several different ways to delete a list item.
- We’ll first look at how we can delete single items from a list.
- And then finish with removing multiple objects.
Method 1 – remove()
Python list.remove()
is a built-in list method that will remove the first item that matches the value that is passed into the function, also known as “remove by value”.
An example showing a variable called food
which is a list containing 3 items called pizza
, fries
, and tacos
.
>>> food = ["pizza", "fries", "tacos"] >>> food ['pizza', 'fries', 'tacos']
To delete fries
from the list, we call the remove
method and pass in fries
as a string.
>>> food.remove("fries") >>> food ['pizza', 'tacos']
This next example shows a list of temperatures.
>>> temperatures = [26, 27, 20, 31, 27, 26] >>> temperatures [26, 27, 20, 31, 27, 26]
Notice there are duplicate items which are 26
and 27
. Calling the remove()
method on 27
will delete the first occurrence which was at the second position.
>>> temperatures.remove(27) >>> temperatures [26, 20, 31, 27, 26]
And if we call remove on 26
,
>>> temperatures.remove(26) >>> temperatures [20, 31, 27, 26] >>>
The first occurrence is deleted and 20
is now the first item in the list.
Method 2 – pop()
The next built-in list method we will show is pop()
. Not only will list.pop()
remove an item from the list, but it also returns the item.
The default item to return and delete, if nothing is passed into the function, is the last one in the list.
This aligns with the Data Structure known as a stack which exhibits the behaviour known as Last In First Out, or LIFO. The terminology to add an item is traditionally called “push
”, and to remove an item is “pop
”. Visually, the stack is like a stack of plates where each additional plate added will rest on top of the existing plate.
Above illustration uses some food items as string objects in a stack. However, in Python the list function called append()
is used to add items to the stack.
>>> food = [] >>> food.append("pizza") >>> food.append("fries") >>> food.append("tacos") >>> food ['pizza', 'fries', 'tacos']
After creating our list of 3 items, we call the pop()
method without passing anything into it to remove the last element from the list while assigning the returned value into a variable.
>>> my_lunch = food.pop() >>> food ['pizza', 'fries'] >>> my_lunch 'tacos' >>>
The last item is returned and deleted from the list, and we’re left with pizza
and fries
. The my_lunch
variable now has the tacos
string.
The pop()
method also allows us to remove an item from the list by index. Let’s start off with the three food items again.
>>> food ['pizza', 'fries'] >>> food.append('tacos') >>> food ['pizza', 'fries', 'tacos']
And this time we will remove pizza
. If we pass it in as a string name, it will not work.
>>> food.pop('pizza') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object cannot be interpreted as an integer >>>
Therefore be sure to pass in the index of the item that you want to delete. We’ll return it to a variable called your_lunch
.
>>> your_lunch = food.pop(0) >>> food ['fries', 'tacos'] >>> your_lunch 'pizza' >>>
As you can see, the first element has been removed by its index and saved into the new variable.
Method 3 – clear()
This list method clear()
will remove all items from a list. Let’s first set our food
variable again to a list of three foods.
>>> food = ['pizza', 'fries', 'tacos'] >>> food ['pizza', 'fries', 'tacos'] And call the clear function. >>> food.clear() >>> food [] >>>
As seen above the food
variable is now an empty list.
Method 4 – del
As mentioned in Method 2, we can use the list method pop()
to delete and return an item by specifying its index.
But what if you don’t need the item to be returned?
That’s where the del
keyword comes in.
Let’s make a list of temperatures again. And we will delete the last item which is the number 27 and located at index 9.
>>> temperatures = [19, 20, 19, 25, 19, 22, 19, 30, 17, 27] >>> del temperatures[9] >>> temperatures [19, 20, 19, 25, 19, 22, 19, 30, 17]
The del
statement will work with Python slicing and negative indexing too as seen in the next examples.
>>> temperatures = [19, 20, 19, 25, 19, 22, 19, 30, 17, 27] >>> del temperatures[-1] >>> temperatures [19, 20, 19, 25, 19, 22, 19, 30, 17]
Slicing can be used to remove multiple items from a list.
Let’s specify deletion of every second item starting from 0 to 7, which is the value 19.
>>> temperatures = [19, 20, 19, 25, 19, 22, 19, 30, 17, 27] >>> del temperatures[0:7:2] >>> temperatures [20, 25, 22, 30, 17, 27] >>>
And lastly, we can use the del
statement to remove all elements from the list, similar to the list method clear()
.
>>> temperatures = [19, 20, 19, 25, 19, 22, 19, 30, 17, 27] >>> del temperatures[:] >>> temperatures [] >>>
An alternate way to delete all items by replacing all the elements with an empty list using a Python feature called slice assignment.
>>> temperatures = [19, 20, 19, 25, 19, 22, 19, 30, 17, 27] >>> temperatures[:] = [] >>> temperatures [] >>>
Method 5 – List Comprehension
As seen from Method 4 we can remove multiple items from a list using slicing by specifying a range and step.
However, what if we need to remove multiple items based on a condition?
That’s where we can use list comprehension. Consider the following example where we need a list of all letters, numbers, and symbols.
We’ll use the string
module. This has a built-in constant called printable
, which is made up of all the printable characters.
>>> import string >>> string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
Notice the last few characters have backslashes to denote tab, newline, return, etc.
And if we print it to the screen, we can see there’s whitespace in the output.
>>> print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ >>>
Let’s use list comprehension to delete the whitespace. Luckily the string
module also includes a constant for that!
>>> string.whitespace ' \t\n\r\x0b\x0c' >>>
This will help with specifying our condition for the list comprehension.
First, let’s create our list of printable characters using list comprehension.
>>> all_chars = [x for x in string.printable] >>> all_chars ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', ' ', '\t', '\n', '\r', '\x0b', '\x0c'] >>>
Now let’s use list comprehension again to delete all the whitespace by setting a condition that as long as the characters are not in the whitespace constant, they will remain in the list.
>>> all_chars = [x for x in all_chars if x not in string.whitespace] >>> all_chars ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~'] >>>
That did the trick! Now our list is left with printable characters except for the whitespaces.
Another quick example: We need a list of even numbers from 1 to 100.
Start by making a list of numbers in that range.
>>> even_numbers = [x for x in range(1,101)] >>> even_numbers [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
Then use list comprehension to check if each number has a remainder of 0 when divided by 2.
>>> even_numbers = [x for x in even_numbers if x % 2 == 0] >>> even_numbers [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100] >>>
Conclusion
Today we went over 5 different methods to delete an object from a list in Python. The first 3 methods are built-in list functions: remove
, pop
, and clear
.
These are used to delete single items from a list.
Depending on your situation, you can either specify the object’s value with the remove()
function, or its index with the pop()
function. Remember the pop()
function will return the object, so if it’s not needed in your program you can use the del
statement.
Additionally, with del
, we can specify a range of objects to remove by using Python slicing.
We also looked at different ways to remove all elements from a list with del
, clear, and by replacing all elements with an empty list.
And finally, we used list comprehension to delete list items based on a condition.
Thanks for joining me. I had a blast writing this article, and look forward to writing the next one!