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

后端 未结 21 1875
我寻月下人不归
我寻月下人不归 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:18

    Here's how to do it inplace (without list comprehension):

    def remove_all(seq, value):
        pos = 0
        for item in seq:
            if item != value:
               seq[pos] = item
               pos += 1
        del seq[pos:]
    

提交回复
热议问题