To remove an element from a list in Python, you can use the `remove()` method. This method takes the element to be removed as its argument and removes the first occurrence of that element from the list.
If the element is not found, the `remove()` method will raise a `ValueError` exception. For example, the following code removes the element `’apple’` from the list `fruits`:
fruits = ['apple', 'banana', 'cherry']
fruits.remove('apple')
print(fruits) # Output: ['banana', 'cherry']
If you want to remove all occurrences of an element from a list, you can use the `while` loop as follows:
fruits = ['apple', 'banana', 'cherry', 'apple', 'banana']
while 'apple' in fruits:
fruits.remove('apple')
print(fruits) # Output: ['banana', 'cherry', 'banana']
About Author
Discover more from SURFCLOUD TECHNOLOGY
Subscribe to get the latest posts sent to your email.