Remove the last N elements of a list

前端 未结 7 733
傲寒
傲寒 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:50

    if you wish to remove the last n elements, in other words, keep first len - n elements:

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

    Note: This is not an in memory operation. It would create a shallow copy.

提交回复
热议问题