Remove the last N elements of a list

前端 未结 7 758
傲寒
傲寒 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 02:07

    Should be using this:

    a[len(a)-n:] = []
    

    or this:

    del a[len(a)-n:]
    

    It's much faster, since it really removes items from existing array. The opposite (a = a[:len(a)-1]) creates new list object and less efficient.

    >>> timeit.timeit("a = a[:len(a)-1]\na.append(1)", setup="a=range(100)", number=10000000)
    6.833014965057373
    >>> timeit.timeit("a[len(a)-1:] = []\na.append(1)", setup="a=range(100)", number=10000000)
    2.0737061500549316
    >>> timeit.timeit("a[-1:] = []\na.append(1)", setup="a=range(100)", number=10000000)
    1.507638931274414
    >>> timeit.timeit("del a[-1:]\na.append(1)", setup="a=range(100)", number=10000000)
    1.2029790878295898
    

    If 0 < n you can use a[-n:] = [] or del a[-n:] which is even faster.

提交回复
热议问题