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

前端 未结 7 914
遇见更好的自我
遇见更好的自我 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']
    
    0 讨论(0)
  • 2021-02-03 17:40

    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)
    
    0 讨论(0)
  • 2021-02-03 17:46

    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.

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

    How about list comprehension?

    a = [x for x in a if x != 10]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题