How to remove an element from a list by index

后端 未结 18 2877
闹比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 04:00

    Use del and specify the index of the element you want to delete:

    >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> del a[-1]
    >>> a
    [0, 1, 2, 3, 4, 5, 6, 7, 8]
    

    Also supports slices:

    >>> del a[2:4]
    >>> a
    [0, 1, 4, 5, 6, 7, 8, 9]
    

    Here is the section from the tutorial.

提交回复
热议问题