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
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.