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

前端 未结 7 919
遇见更好的自我
遇见更好的自我 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:49

    I'd personally consider using a set instead of a list as long as the order of your elements isn't necessarily important. Then you can use the discard method:

    >>> S = set(range(10))
    >>> S
    set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    >>> S.remove(10)
    Traceback (most recent call last):
      File "", line 1, in 
    KeyError: 10
    >>> S.discard(10)
    >>> S
    set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    

提交回复
热议问题