Python Remove Specified Element from List

Document 对象参考手册Python3 Examples

In Python, if you want to remove a specified element from a list, you can use theremove()method. This method removes the first matching element from the list. If there are multiple identical elements in the list, only the first one will be removed.

Example

# Create a list containing multiple elements
my_list = [1, 2, 3, 4, 3, 5]

# Remove element 3 from the list
my_list.remove(3)

# Print the modified list
print(my_list)

Code explanation:

  1. my_list = [1, 2, 3, 4, 3, 5]: Create a list containing multiple elements.
  2. my_list.remove(3): Useremove()method to remove the first element with value 3 from the list.
  3. print(my_list): Print the modified list.

Output result:

[1, 2, 4, 3, 5]

It can be seen that the first element with value 3 in the list is removed, while the second element with value 3 remains in the list.

Document 对象参考手册Python3 Examples

Other extensions