Search code examples
pythonlistindexingdel

More efficient way to delete list item with index Python


More efficient way to delete list item with index Python

What is a more efficient alternative to:

    del List[List.index(aString)]

Solution

  • You can use list.remove as below

    x = ['a', 'b', 'c', 'a']
    x.remove('a')
    print(x)
    # ['b', 'c', 'a']
    
    x.remove('d')
    # ValueError
    

    Note that if there is no 'd' in your list then it will throw a ValueError, you could get around this by using a try...except... block

    try:
        x.remove('d')
    except ValueError:
        pass