There can be cases where you do not want to remove just one element from a list, but many elements in one step.
In this case, the remove()
method does not help us since it simply removes the first instance that it finds.
Let us take a list as an example:
my_list = ["a", "b", "c", "d", "e", "f", "g"]
Let us assume that we want to delete c
and d
from that list. We can do that in the following way where we omit cd
and d
entirely:
my_list = my_list[:2] + my_list[4:]
To remove multiple elements in just one step, we need to actually use del
method.
del my_list[2:4]
print(my_list) # ['a', 'b', 'e', 'f', 'g']
That’s pretty much it.
I hope you find this useful.