x : ( value ) first matching value to be removed
my_list=['Alex','Ronald','John']
my_list.remove('Ronald')
print(my_list)
Output is here
['Alex', 'John']
my_list=['Alex','Ronald','John','Ronald','Ronn']
my_list.remove('Ronald')
print(my_list)
Output ( 2nd matching element Ronald is not removed. )
['Alex', 'John', 'Ronald', 'Ronn']
If the element to be removed is not found, Python will raise a ValueError. We can handle this with a try-except block:
my_list = ['Alex', 'John']
try:
my_list.remove('Ronald')
except ValueError:
print("Element not found!")
In data cleaning tasks, we can use remove() to eliminate unwanted values:
data = ['valid', 'invalid', 'valid']
data.remove('invalid') # Cleans up the list
print(data) # Output: ['valid', 'valid']
You can use remove() inside loops to dynamically adjust lists:
numbers = [5, 3, 2, 1, 3, 4]
while 3 in numbers:
numbers.remove(3)
print(numbers) # Output: [5, 2, 1, 4]
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.