How to remove an element from a list by index

后端 未结 18 3362
闹比i
闹比i 2020-11-22 03:22

How do I remove an element from a list by index in Python?

I found the list.remove method, but say I want to remove the last element, how do I do this?

18条回答
  •  我寻月下人不归
    2020-11-22 03:53

    It has already been mentioned how to remove a single element from a list and which advantages the different methods have. Note, however, that removing multiple elements has some potential for errors:

    >>> l = [0,1,2,3,4,5,6,7,8,9]
    >>> indices=[3,7]
    >>> for i in indices:
    ...     del l[i]
    ... 
    >>> l
    [0, 1, 2, 4, 5, 6, 7, 9]
    

    Elements 3 and 8 (not 3 and 7) of the original list have been removed (as the list was shortened during the loop), which might not have been the intention. If you want to safely remove multiple indices you should instead delete the elements with highest index first, e.g. like this:

    >>> l = [0,1,2,3,4,5,6,7,8,9]
    >>> indices=[3,7]
    >>> for i in sorted(indices, reverse=True):
    ...     del l[i]
    ... 
    >>> l
    [0, 1, 2, 4, 5, 6, 8, 9]
    

提交回复
热议问题