To remove a specific element from a list in Python, you can use the `remove` method of the list object.
In this example,
my_list
with some elements.remove
method of the list to remove the element if it is present.my_list = [1, 2, 3, 4, 5]
value_to_remove = 3
my_list.remove(value_to_remove)
print(f'Modified list after removing {value_to_remove}: {my_list}')
Modified list after removing 3: [1, 2, 4, 5]
In this example,
my_list
with some elements.remove
method of the list to attempt to remove the element.remove
method raises a ValueError
.my_list = [1, 2, 3, 4, 5]
value_to_remove = 6
try:
my_list.remove(value_to_remove)
except ValueError:
pass
print(f'Original list: {my_list}')
Original list: [1, 2, 3, 4, 5]
In this tutorial, we learned How to Remove Specific Element from a List in Python language with well detailed examples.