[Python] Is there a simple way to delete a list element by value?

Discussão em 'Python' iniciado por Stack, Março 18, 2025.

  1. Stack

    Stack Membro Participativo

    I want to remove a value from a list if it exists in the list (which it may not).

    a = [1, 2, 3, 4]
    b = a.index(6)

    del a
    print(a)


    The above gives the error:

    ValueError: list.index(x): x not in list


    So I have to do this:

    a = [1, 2, 3, 4]

    try:
    b = a.index(6)
    del a
    except:
    pass

    print(a)


    But is there not a simpler way to do this?

    Continue reading...

Compartilhe esta Página