Removing an Element with a Specific Value using remove() Function
The remove()
function can be used to find and remove a specific value from a list. This function removes only the first appearance of the specified value in the list.
How to Use remove()?
To remove a specific value from a list using the remove()
function, pass the value to be removed as a parameter.
For example, in the code below, colors.remove('Blue')
removes the element with the value 'Blue' from the list.
colors = ['Red', 'Blue', 'Green', 'Blue']
colors.remove('Blue')
print("colors:", colors)
# colors: ['Red', 'Green', 'Blue']
Although the 'Blue'
appears twice in the colors
variable, the remove()
function only removes the first 'Blue'
element found.
If the value does not exist in the list, a ValueError
is raised.
How to Handle ValueError?
When using the remove()
function, a ValueError
occurs if the value is not in the list.
To prevent this, use an if
statement to check if the value exists in the list before calling the remove()
function.
colors = ['Red', 'Yellow', 'Green']
if 'Blue' in colors:
colors.remove('Blue')
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.