Remove the last N elements of a list

前端 未结 7 764
傲寒
傲寒 2021-02-01 01:41

Is there a a better way to remove the last N elements of a list.

for i in range(0,n):
    lst.pop( )
7条回答
  •  温柔的废话
    2021-02-01 01:47

    I see this was asked a long ago, but none of the answers did it for me; what if we want to get a list without the last N elements, but keep the original one: you just do list[:-n]. If you need to handle cases where n may equal 0, you do list[:-n or None].

    >>> a = [1,2,3,4,5,6,7]
    >>> b = a[:-4]
    >>> b
    [1, 2, 3]
    >>> a
    [1, 1, 2, 3, 4, 5, 7]
    

    As simple as that.

提交回复
热议问题