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

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

    A better way to do this would be

    source_list = list(filter(lambda x: x != element_to_remove,source_list))
    

    Because in a more complex program, the exception of ValueError could also be raised for something else and a few answers here just pass it, thus discarding it while creating more possible problems down the line.

提交回复
热议问题