Last updated: Apr 9, 2024
Reading timeยท6 min
To remove list elements while iterating over it:
for
loop to iterate over a copy of the list.list.remove()
method to remove the items that meet the condition.my_list = [22, 33, 66, 77, 99] for item in my_list.copy(): if item < 50: my_list.remove(item) print(my_list) # ๐๏ธ [66, 77, 99]
We used the list.copy()
method to get a copy of the list.
my_list = [22, 33, 66, 77, 99] print(my_list.copy()) # ๐๏ธ [22, 33, 66, 77, 99]
The list.copy() method returns a shallow copy of the object on which the method was called.
However, we can iterate over a copy of the list and remove items from the original list.
my_list = [22, 33, 66, 77, 99] for item in my_list.copy(): if item < 50: my_list.remove(item) print(my_list) # ๐๏ธ [66, 77, 99]
On each iteration in the for
loop, we check if the current item is less than
50
and remove the elements that meet the condition.
You might also see examples that use the my_list[:]
syntax to get a shallow
copy of the list by using
list slicing.
my_list = [22, 33, 66, 77, 99] for item in my_list[:]: if item < 50: my_list.remove(item) print(my_list) # ๐๏ธ [66, 77, 99]
We used the my_list[:]
syntax to get a slice that represents the entire list.
my_list = [22, 33, 66, 77, 99] print(my_list[:]) # ๐๏ธ [22, 33, 66, 77, 99]
list.copy()
method, it creates a shallow copy of the list that we can iterate over.In general, the list.copy()
method is a little more readable than using a
slice that represents the entire list.
Here is another example.
my_list = [None, 22, 33, None, 66, 77, None, 99] for item in my_list.copy(): if item is None: my_list.remove(item) print(my_list) # ๐๏ธ [22, 33, 66, 77, 99]
We used a for
loop to
remove all None
values from a list while
iterating over it.
The most important thing to note when removing items from a list in a for
loop
is to use the list.copy()
method to iterate over a copy of the list.
If you try to iterate over the original list and remove items from it, you might run into difficult-to-locate bugs.
If you aren't removing or adding new items to the list when iterating over it, you don't have to create a copy.
my_list = [5, 11, 25, 7, 30] for index, item in enumerate(my_list): if item <= 10: my_list[index] = 10 print(my_list) # ๐๏ธ [10, 11, 25, 10, 30]
We used the enumerate()
function to get access to the index of the current
iteration.
The enumerate() function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the item.
The example checks if the current list item is less than or equal to 10
and if
the condition is met, the item gets set to 10
.
Alternatively, you can use a list comprehension.
The list comprehension will return a new list containing only the elements that match the condition.
my_list = [77, 105, 123, 88, 199] new_list = [item for item in my_list if item > 100] print(new_list) # ๐๏ธ [105, 123, 199]
We used a list comprehension to remove the items from a list while iterating.
On each iteration, we check if the current item is greater than 100
and return
the result.
The new list will only contain values that are greater than 100
.
The list comprehension in the example doesn't mutate the original list.
If you need to mutate the original list, assign the result to a slice that represents the entire list.
You can update the list in place by using a slice assignment.
my_list = [77, 105, 123, 88, 199] my_list[:] = [item for item in my_list if item > 100] print(my_list) # ๐๏ธ [105, 123, 199]
We used the my_list[:]
syntax to get a slice that represents the entire list,
so we can assign to the variable directly.
my_list = [77, 105, 123, 88, 199] print(my_list[:]) # ๐๏ธ [77, 105, 123, 88, 199]
The slice my_list[:]
represents the entire list, so when we use it on the
left-hand side, we are assigning to the entire list.
This approach changes the contents of the original list.
You can also use the filter()
function to remove items from a list while
iterating.
my_list = [77, 105, 123, 88, 199] new_list = list(filter( lambda x: x > 100, my_list )) print(new_list) # ๐๏ธ [105, 123, 199]
The filter() function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.
The lambda function we passed to filter
gets called with each element of the
list.
On each iteration, we check if the current item is greater than 100
and return
the result.
The filter
object only contains the elements for which the condition is met.
The last step is to convert the filter
object to a list using the
list() class.
range()
You can also use the range()
class to
remove items from a list while iterating over it.
my_list = [77, 105, 123, 88, 199, 4, 1, 5] for index in range(len(my_list) - 1, -1, -1): print(index) if my_list[index] < 100: my_list.pop(index) # ๐๏ธ [105, 123, 199] print(my_list)
The range() class is commonly used for looping
a specific number of times in for
loops and takes the following arguments:
Name | Description |
---|---|
start | An integer representing the start of the range (defaults to 0 ) |
stop | Go up to, but not including the provided integer |
step | Range will consist of every N numbers from start to stop (defaults to 1 ) |
We used a negative step to reverse the range.
my_list = [77, 105, 123, 88, 199, 4, 1, 5] # ๐๏ธ [7, 6, 5, 4, 3, 2, 1, 0] print(list(range(len(my_list) - 1, -1, -1)))
The range
object is not dependent on the list in any way, so removing items
from the list doesn't influence the number of iterations.
filterfalse()
You can also use the filterfalse
method from the itertools
module to remove
items from the list while iterating over it.
from itertools import filterfalse my_list = [77, 105, 123, 88, 199, 4, 1, 5] def check_func(num): return num < 100 my_list[:] = filterfalse(check_func, my_list) print(my_list) # ๐๏ธ [105, 123, 199]
Make sure to import the filterfalse
method as shown in the code sample.
The filterfalse
method takes a predicate and an iterable and calls the
function with each item in the iterable.
The method returns a list containing the items for which the function returned
false
.
In the example, the method returns a list containing the items that are not less
than 100
.
Which approach you pick is a matter of personal preference. I'd use a for
loop
with list.copy()
because I find it quite direct and intuitive.
You can learn more about the related topics by checking out the following tutorials: