Removing Elements from a List by Their Value in Python
Elements can be removed from the list by their value. To do this, use the remove
method. We pass the value we need to its parameter:
lst = [1, 2, 3]
lst.remove(1)
print(lst) # [2, 3]
In the case where you have two identical elements in your list, the remove
method will only remove the first match:
lst = [1, 2, 3, 1]
lst.remove(1)
print(lst) # [2, 3, 1]
Given a list:
lst = ['a', 'b', 'c', 'd', 'e']
Remove the element with value 'c'
.
Given a list:
lst = ['a', 'b', 'c', 'd', 'e']
Remove the element with value 'b'
.
Given a list:
lst = ['b', 1, 2, 'b', 'c', 2]
Remove all identical elements from the list one by one.