Deleting the first element of a list

Erik Max Francis max at alcyone.com
Wed Oct 2 18:53:36 EDT 2002


JB wrote:

> Is using del to delete the first element (that is, the 0th
> element) of a list faster than x = x[1:]?

For the long answer, try it out yourself.  Write to programs that do
these operations many, many times, and then time them.  Make sure that
you use lists that are representative of whatever sample you're shooting
for.  To test the worst case, use outrageously long lists.

Slicing creates new lists, so invariably the slicing mechanism is going
to be more expensive, since a new object has to be created each time. 
Testing by taking 1000-element lists and trimming the first element off
until the list is empty, indicates that the slicing method takes about 3
times longer.

The short answer, though, is not to optimize prematurely.  That's the
First Rule of Optimization:  Don't bother optimizing until you have
quantitative information about where the bottlenecks truly are.  This
concept is especially powerful in a high-level language like Python; the
very choice of using Python means that you're willing to trade raw speed
for flexibility.  If you're overconcerned with squeezing every last bit
of CPU power right from the start, then Python (or any other high-level
language) was probably not a good choice of languages.

Though I'm overstating it.  Certainly premature optimization is often
wasted effort, but given tiny, equivalent, and readable ways of doing
the same very simple thing, there's really no reason not to prefer the
one that is faster.  This is one of those cases; use del L[0] rather
than L = L[1:].

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Punctuality is the virtue of the bored.
\__/ Evelyn Waugh
    Erik Max Francis' bookmarks / http://www.alcyone.com/max/links/
 A highly categorized list of Web links.



More information about the Python-list mailing list