124

I need to remove the first n elements from a list of objects in Python 2.7. Is there an easy way, without using loops?

4
  • 1
    x.pop(5), del x[5] or x.remove("cow"). The first two removes by index and the later removes by search criteria. The second can be combined by doing del x[2:5] which delites indexes 2-5
    – Torxed
    Commented Nov 10, 2015 at 9:24
  • why the 5? if i have for example [a,b,c,d,e,f,g...z] and want to keep only [f,g...z]?
    – RedVelvet
    Commented Nov 10, 2015 at 9:26
  • Then you'd want to do pos = x.index("f"); end = x.index("z"); del x[pos:end] You'd have to take in to account that z might exist before f and use pos as a starting poiint when searching for z etc but you get the idea.
    – Torxed
    Commented Nov 10, 2015 at 9:27
  • 1
    maybe you want list[n:]
    – juankirr
    Commented Nov 10, 2015 at 9:29

7 Answers 7

178

You can use list slicing to archive your goal.

Remove the first 5 elements:

n = 5
mylist = [1,2,3,4,5,6,7,8,9]
newlist = mylist[n:]
print newlist

Outputs:

[6, 7, 8, 9]

Or del if you only want to use one list:

n = 5
mylist = [1,2,3,4,5,6,7,8,9]
del mylist[:n]
print mylist

Outputs:

[6, 7, 8, 9]
61

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:

list + pop(0)

In [30]: %%timeit
   ....: help=range(10000)
   ....: while help:
   ....:     help.pop(0)
   ....:
100 loops, best of 3: 17.9 ms per loop

deque + popleft()

In [33]: %%timeit
help=deque(range(10000))
while help:
    help.popleft()
   ....:
1000 loops, best of 3: 812 µs per loop
4
  • 1
    using del mylist[:n] it's still inefficient ?
    – RedVelvet
    Commented Nov 10, 2015 at 9:38
  • I'm curious: how can pop be efficient if list is array backed? wiki.python.org/moin/TimeComplexity Commented Jun 14, 2017 at 13:34
  • @RedVelvet: Yes. Nevertheless, regarding deque vs list keep in mind, that deque does not have all features which list have. on bigger shifts (1 million rows) I found del mylist[1000000:] is around the same execution as deque.popleft() for all the rows.. So it depends on your use case.
    – gies0r
    Commented Jul 23, 2019 at 22:10
  • wow, is it actually in the specs that you can iterate over a deque while you're calling popleft() on it?
    – Christian
    Commented Apr 28, 2020 at 11:00
5
l = [1, 2, 3, 4, 5]
del l[0:3] # Here 3 specifies the number of items to be deleted.

This is the code if you want to delete a number of items from the list. You might as well skip the zero before the colon. It does not have that importance. This might do as well.

l = [1, 2, 3, 4, 5]
del l[:3] # Here 3 specifies the number of items to be deleted.
4

The most efficient approach, memory-wise and complexity-wise, is this:

popped_items = lst[:n]
del lst[:n]

It allows you to first obtain the first n items and only allocate the space for them. And then, you delete them from the initial list, which is also fast.

2

Try to run this code:

del x[:N]
2

Let's say you have this list:

mylist = [1,2,3,4,5,6,7,8,9]

And you want to remove the x last elements and store them in another list

newlist = [mylist.pop() for _ in range(x)]

You can modify the argument you pass to pop in order to remove elements from the beginning

newlist = [mylist.pop(0) for _ in range(x)]

Or leave the first element and remove x elements after

newlist = [mylist.pop(1) for _ in range(x)]
-2
l = [5,1,4,2,3,6]

Sort the list from smallest to largest

l.sort()

Remove the first 2 items in the list

for _ in range(2)
    l.remove(l[0])

Print the list

print(l)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.