How to remove the first 50 items in a list without copying it?

Viewed 104

I have a very large list, and I'd like to iteratively remove the first 50 elements without copying it (as for example something like list[50:]).

My initial thought was by doing:

[list.pop(0) for i in range(50)]

What would be the most performant way to do this?

2 Answers

You can use the del keyword. So to remove the first 50 elements you can do:

del list[:50]

Update the list in place with a slice that removes the first 50 items:

list[:] = list[50:]

Update

I ran some timeit tests which actually show del list[:50] to be approx 2X faster.

Related