How to remove an element from a list by index

后端 未结 18 3377
闹比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:57

    One can either use del or pop, but I prefer del, since you can specify index and slices, giving the user more control over the data.

    For example, starting with the list shown, one can remove its last element with del as a slice, and then one can remove the last element from the result using pop.

    >>> l = [1,2,3,4,5]
    >>> del l[-1:]
    >>> l
    [1, 2, 3, 4]
    >>> l.pop(-1)
    4
    >>> l
    [1, 2, 3]
    

提交回复
热议问题