Python lists were not made to operate on the beginning of the list and are very ineffective at this operation.
While you can write
mylist = [1, 2 ,3 ,4]
mylist.pop(0)
It's very inefficient.
If you only want to delete items from your list, you can do this with del
:
del mylist[:n]
Which is also really fast:
In [34]: %%timeit
help=range(10000)
while help:
del help[:1000]
....:
10000 loops, best of 3: 161 µs per loop
If you need to obtain elements from the beginning of the list, you should use collections.deque
by Raymond Hettinger and its popleft()
method.
from collections import deque
deque(['f', 'g', 'h', 'i', 'j'])
>>> d.pop() # return and remove the rightmost item
'j'
>>> d.popleft() # return and remove the leftmost item
'f'
A comparison:
In [30]: %%timeit
....: help=range(10000)
....: while help:
....: help.pop(0)
....:
100 loops, best of 3: 17.9 ms per loop
In [33]: %%timeit
help=deque(range(10000))
while help:
help.popleft()
....:
1000 loops, best of 3: 812 µs per loop