Pop multiple items from the beginning and end of a list

You could slice out a new list, keeping the old list as is:

mylist=['a','b','c','d','e','f','g','h','i']
newlist = mylist[2:-2]

newlist now returns:

['c', 'd', 'e', 'f', 'g']

You can overwrite the reference to the old list too:

mylist = mylist[2:-2]

Both of the above approaches will use more memory than the below.

What you're attempting to do yourself is memory friendly, with the downside that it mutates your old list, but popleft is not available for lists in Python, it's a method of the collections.deque object.

This works well in Python 3:

for x in range(2):
    mylist.pop(0)
    mylist.pop()

In Python 2, use xrange and pop only:

for _ in xrange(2):
    mylist.pop(0)
    mylist.pop()

Fastest way to delete as Martijn suggests, (this only deletes the list's reference to the items, not necessarily the items themselves):

del mylist[:2]
del mylist[-2:]

From a performance point of view:

  • mylist = mylist[2:-2] and del mylist[:2];del mylist[-2:] are equivalent
  • they are around 3 times faster than the first solution for _ in range(2): mylist.pop(0); mylist.pop()

Code

iterations = 1000000
print timeit.timeit('''mylist=range(9)\nfor _ in range(2): mylist.pop(0); mylist.pop()''', number=iterations)/iterations
print timeit.timeit('''mylist=range(9)\nmylist = mylist[2:-2]''', number=iterations)/iterations
print timeit.timeit('''mylist=range(9)\ndel mylist[:2];del mylist[-2:]''', number=iterations)/iterations

output

1.07710313797e-06

3.44465017319e-07

3.49956989288e-07