accessing front of a list

Erik Max Francis max at alcyone.com
Tue Nov 26 20:24:14 EST 2002


Hans Nowak wrote:

> You probably want pop(0):
> 
>  >>> a = range(5)
>  >>> x = a.pop(0)
>  >>> x
> 0
>  >>> a
> [1, 2, 3, 4]
> 
> ...but destructive processing of lists this way is relatively rare,
> IMHO.

It's also worth noting that it's an O(n) operation, since the list
elements have to be shuffled down when inserting or deleting one.  If
you're iterating over the whole sequence, that makes it O(n^2).

If that's the case, you're probably better off reversing the list (an
O(n) operation) and then popping them off the end (with L.pop()), which
is an O(1) operation.  That gives you two separate O(n) operations,
instead of an O(n) operation within an O(n) operation (which makes it
O(n^2)).

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Everyone wants to look good at his own funeral.
\__/ Louis Wu
    PyUID / http://www.alcyone.com/pyos/uid/
 A module for generating "unique" IDs in Python.



More information about the Python-list mailing list