Remove the last N elements of a list

前端 未结 7 759
傲寒
傲寒 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

    This is one of the cases in which being pythonic doesn't work for me and can give hidden bugs or mess. None of the solutions above works for the case n=0. Using l[:len(l)-n] works in the general case:

    l=range(4)
    for n in [2,1,0]: #test values for numbers of points to cut
        print n,l[:len(l)-n]
    

    This is useful for example inside a function to trim edges of a vector, where you want to leave the possibility not to cut anything.

    0 讨论(0)
提交回复
热议问题