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

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

    A good and thread-safe way to do this is to just try it and ignore the exception:

    try:
        a.remove(10)
    except ValueError:
        pass  # do nothing!
    
    0 讨论(0)
提交回复
热议问题