How to remove an element from a list by index

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

    This depends on what you want to do.

    If you want to return the element you removed, use pop():

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

    However, if you just want to delete an element, use del:

    >>> l = [1, 2, 3, 4, 5]
    >>> del l[2]
    >>> l
    [1, 2, 4, 5]
    

    Additionally, del allows you to use slices (e.g. del[2:]).

提交回复
热议问题