Python Delete a Specified Element from a List
In Python, if you want to delete a specified element from a list, you can use the remove() method. This method removes the first matching element in the list. If the list contains several identical elements, only the first one is removed.
Example
Create a list containing several elements
my_list
=
[
1
,
2
,
3
,
4
,
3
,
5
]
Delete the element 3 from the list
my_list.
remove
(
3
)
Print the modified list
(
my_list
)
Code analysis:
my_list = [1, 2, 3, 4, 3, 5]: Create a list containing several elements.my_list.remove(3): When usingremove()The method removes the first element with the value 3 from the list.print(my_list): Print the modified list.
Output result:
[1, 2, 4, 3, 5]
As you can see, the first element with value 3 was removed from the list, while the second element with value 3 remains in the list.
Python3 Examples