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

感情迁移 提交于 2020-12-28 10:42:32

问题


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:

>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a.remove(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> a.remove(9)

回答1:


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!



回答2:


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 "<stdin>", line 1, in <module>
KeyError: 10
>>> S.discard(10)
>>> S
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])



回答3:


As an alternative to ignoring the ValueError

try:
    a.remove(10)
except ValueError:
    pass  # do nothing!

I think the following is a little more straightforward and readable:

if 10 in a:
    a.remove(10)



回答4:


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.




回答5:


How about list comprehension?

a = [x for x in a if x != 10]



回答6:


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']



回答7:


you have typed wrong input. syntax: list.remove(x)

and x is the element of your list. in remove parenthesis ENTER what already have in your list. ex: a.remove(2)

i have entered 2 because it has in list. I hape this data help you.



来源:https://stackoverflow.com/questions/9915339/how-can-i-ignore-valueerror-when-i-try-to-remove-an-element-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!