How can I ignore ValueError when I try to remove an element from a list?

前端 未结 7 913
遇见更好的自我
遇见更好的自我 2021-02-03 17:19

How can I ignore the \"not in list\" error message if I call a.remove(x) when x is not present in list a?

This is my situation:

7条回答
  •  [愿得一人]
    2021-02-03 17:38

    When I only care to ensure the entry is not in a list, dict, or set I use contextlib like so:

    import contextlib
    
    some_list = []
    with contextlib.suppress(ValueError):
        some_list.remove(10)
    
    some_set = set()
    some_dict = dict()
    with contextlib.suppress(KeyError):
        some_set.remove('some_value')
        del some_dict['some_key']
    

提交回复
热议问题