There are several methods in Python for removing items from a list, each with a different use case and behavior:
- To remove all items from the list, use the
clear()
method. - To remove the last item or a specific item by index, use the
pop()
method. - To remove an item by value, use the
remove()
method. - To remove items by index or by slicing through lists, use the
del
statement. - To remove items based on a condition, use list comprehension or the
filter()
function.
Let’s take a closer look at each method.
Remove an Item by Value – remove()
The remove()
method removes a single item from the list.
The method searches for the first occurrence of the specified item and removes it. If the specified item is not found in the list, it raises a ValueError
exception.
Syntax
The syntax of the remove()
method is as follows:
list.remove(item)
Parameter | Condition | Description |
item | Required | Any item you want to remove |
Examples
# Remove 'green'
L = ['red', 'green', 'blue']
L.remove('green')
print(L)
# Output: ['red', 'blue']
# Remove item from the nested list
L = ['red', 'green', [1, 2, 3]]
L.remove([1, 2, 3])
print(L)
# Output: ['red', 'green']
Please keep in mind that if there are multiple occurrences of the item you want to remove, only the first one found is removed.
L = ['red', 'green', 'blue', 'red', 'red']
L.remove('red')
print(L)
# Output: ['green', 'blue', 'red', 'red']
If the specified item is not found in the list, it raises a ValueError exception.
L = ['red', 'green', 'blue']
L.remove('yellow')
# ValueError: list.remove(x): x not in list
To avoid such an exception, you can check if the item exists in the list by using the in
operator inside an if
statement.
L = ['red', 'green', 'blue']
if 'yellow' in L:
L.remove('yellow')
The remove()
method removes an item based on the specified value, not by index. If you want to delete list items based on their index, use the pop() method or the del
keyword.
Remove an Item by Index – pop()
The pop()
method removes a single list item at the specified index and returns it. If no index is specified, it removes and returns the last item in the list.
This method is especially useful for data structures like stacks and queues where you need to retrieve elements in a specific order.
Syntax
The syntax of the pop()
method is:
list.pop(index)
Parameter | Condition | Description |
index | Optional | An index of the item you want to remove and return. Default value is -1. |
Examples
# Remove 2nd list item
L = ['red', 'green', 'blue']
L.pop(1)
print(L)
# Output: ['red', 'blue']
Unlike other list methods, that only modify the list, pop()
returns the value of the removed element. This allows you to capture the element for further use.
L = ['red', 'green', 'blue']
x = L.pop(1)
# removed item
print(x)
# Output: green
When you don’t specify the index on pop()
, it assumes the parameter to be -1 and removes the last item.
# Remove last item
L = ['red', 'green', 'blue']
L.pop()
print(L)
# Output: ['red', 'green']
pop()
supports negative indexing, so you can use negative numbers to remove elements from the end of the list. For example, pop(-1)
removes the last element while pop(-2)
removes the second-to-last element.
# Remove second-to-last list item
L = ['red', 'green', 'blue']
L.pop(-2)
print(L)
# Output: ['red', 'blue']
If the list is empty or the index is out of range, pop()
raises an IndexError
. This ensures that the method is only used on lists with accessible elements.
L = []
L.pop()
# IndexError: pop from empty list
Remove Items by Index or Slice – del Statement
The del
keyword in Python is a powerful statement used for deleting objects. When it comes to lists, del
can remove individual items, a range of items (slices), or the entire list itself.
Examples
To remove a single item from a list by its index, you use the del
keyword followed by the list and the index of the item you want to remove.
# Remove 2nd list item
L = ['red', 'green', 'blue']
del L[1]
print(L)
# Output: ['red', 'blue']
If you specify an index that is outside the range of the list, Python raises an IndexError
.
L = ['red', 'green', 'blue']
del L[3]
# IndexError: list assignment index out of range
del
can also remove a range of items at once. This is particularly useful for removing sections of a list based on their positions.
To remove a range of items, you can use slicing syntax with start
, stop
, and step
values:
del list[start:stop:step]
Where, start
specifies the starting index (inclusive).
stop
specifies the ending index (exclusive).
step
is optional and indicates the increment between indices (defaults to 1).
For example, to remove items from index 1 (inclusive) to 4 (exclusive), you would do this:
# Remove items from index 1 (inclusive) to 4 (exclusive)
L = ['red', 'green', 'blue', 'yellow', 'black']
del L[1:4]
print(L)
# Output: ['red', 'black']
Using del
with the list variable itself removes the list object from the namespace.
# Delete the entire list
L = ['red', 'green', 'blue']
del L
Remove All Items – clear()
The clear()
method removes all items from the list. This method modifies the list in place, leaving it empty, and does not return any value.
Syntax
The syntax of the clear()
method is straightforward. It does not take any arguments and does not return any value after execution.
list.clear()
Examples
The clear()
method is called directly on the list object you want to clear. Once called, clear()
removes all elements from the list, setting its size to zero.
L = ['red', 'green', 'blue']
L.clear()
print(L)
# Output: []
Please note that clear()
is not the same as assigning an empty list L = []
.
L = []
does not empty the list in place like the clear()
method; instead, it overwrites the variable L
with a different list, which happens to be empty. If anyone else had a reference to the original list, it remains as is, which could cause a problem.
The code below demonstrates the difference between emptying a list using the clear()
method and reassigning a variable to an empty list in terms of how they affect the memory address of the list object.
# Memory address remains the same when using clear()
L = ['red', 'green', 'blue']
print(id(L)) # Output: 1221423858816
L.clear()
print(id(L)) # Output: 1221423858816
# Memory address changes when reassigning to an empty list
L = ['red', 'green', 'blue']
print(id(L)) # Output: 1221422010624
L = []
print(id(L)) # Output: 1221423858816
Equivalent Methods
For Python 2.x or below Python 3.2 users, the clear()
method is not available. You can use the equivalent methods listed below.
- You can remove all items from the list by using the
del
keyword on a start-to-end slice.L = ['red', 'green', 'blue'] del L[:] print(L) # Output: []
- Assigning an empty list to a start-to-end slice produces the same result as
clear()
.L = ['red', 'green', 'blue'] L[:] = [] print(L) # Output: []
- Multiplying a list by 0 using the multiplication assignment operator removes all items from the list in place.
L = ['red', 'green', 'blue'] L *= 0 print(L) # Output: []
Any integer less than or equal to zero will have the same effect.
Remove items based on a condition – List Comprehensions
When you want to remove items from a list that meet a certain condition, you can use list comprehension to create a new list containing only the items you want to keep, essentially filtering out the unwanted ones.
The condition in the list comprehension is set up so that it evaluates to True for items you want to keep while effectively excluding the items you want to remove.
# Remove all ‘red’
L = ['red', 'green', 'blue', 'red', 'red']
L = [x for x in L if x is not 'red']
print(L)
# Output: ['green', 'blue']
# Remove all even numbers
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
L = [num for num in L if num % 2 != 0]
print(L)
# Output: [1, 3, 5, 7, 9]
Remove items based on a condition – filter()
Another way to remove items from a list based on a condition is by using the filter()
function.
Essentially, the filter()
function constructs an iterator from items of an iterable for which a function returns true. Simply put, filter()
allows you to process an iterable and extract elements that satisfy a certain condition.
To remove items from a list using filter()
, you define a function that specifies the condition the items must meet to be included in the result. Items that do not meet the condition are effectively removed in the output.
Syntax
The filter()
function syntax is as follows:
filter(function, iterable)
Parameter | Condition | Description |
function | Required | A function that defines the filtering criteria |
iterable | Required | An iterable from which you want to filter items |
Examples
The example below filters out odd numbers from the list.
def is_even(x):
return x % 2 == 0
L = [1, 2, 3, 4, 5]
L = list(filter(is_even, L))
print(L)
# Output: [2, 4]
filter()
is frequently used in conjunction with lambda functions to specify the filtering condition inline, making the code compact and concise.
L = [1, 2, 3, 4, 5]
L = list(filter(lambda x: x % 2 == 0, L))
print(L)
# Output: [2, 4]