Python: delete a item from a list








  • remove the first matching element:
    if e in list:
    list.remove(e)
  • remove all occurrences:
    while e in list:
    list.remove(e)
  • EAFP style: remove the first occurrence:
    try:
    list.remove(e)
    except ValueError:
    # not in the list
    pass
  • EAFP style: remove all occurrences:

    while True:
    try:
    list.remove(e)
    except ValueError:
    break

EAFP

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.




No comments:

Post a Comment