Remove all occurrences of a value from a list?

后端 未结 23 1893
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 23:45

In Python remove() will remove the first occurrence of value in a list.

How to remove all occurrences of a value from a list?

This is w

23条回答
  •  灰色年华
    2020-11-21 23:56

    Remove all occurrences of a value from a Python list

    lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
    def remove_values_from_list():
        for list in lists:
          if(list!=7):
             print(list)
    remove_values_from_list()
    

    Result: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11

    Alternatively,

    lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
    def remove_values_from_list(remove):
        for list in lists:
          if(list!=remove):
            print(list)
    remove_values_from_list(7)
    

    Result: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11

提交回复
热议问题