Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Delete a Specified Element from a List

Python Delete a Specified Element from a List

Document Object Reference Manual Python3 Examples

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

print

(

my_list

)

Code analysis:

  1. my_list = [1, 2, 3, 4, 3, 5]: Create a list containing several elements.
  2. my_list.remove(3): When using remove() The method removes the first element with the value 3 from the list.
  3. 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.

Document Object Reference Manual Python3 Examples