Daniel Daniel - 6 months ago 27
Python Question

Remove the last N elements of a list

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

for i in range(0,n):
list.pop( )

Answer

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

lst = lst[:n-1]

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

Comments