Is there a simple way to delete a list element by value?

后端 未结 21 1535
我寻月下人不归
我寻月下人不归 2020-11-22 12:20

I want to remove a value from a list if it exists in the list (which it may not).

a = [1, 2, 3, 4]
b = a.index(6)

del a[b]
print(a)

The abov

21条回答
  •  感情败类
    2020-11-22 13:16

    To remove an element's first occurrence in a list, simply use list.remove:

    >>> a = ['a', 'b', 'c', 'd']
    >>> a.remove('b')
    >>> print(a)
    ['a', 'c', 'd']
    

    Mind that it does not remove all occurrences of your element. Use a list comprehension for that.

    >>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
    >>> a = [x for x in a if x != 20]
    >>> print(a)
    [10, 30, 40, 30, 40, 70]
    

提交回复
热议问题