Deleting the first element of a list
Duncan Booth
duncan at NOSPAMrcp.co.uk
Thu Oct 3 04:36:30 EDT 2002
Bruce Dawson <bruce_deletethis_dawson at cygnus-software.com> wrote in
news:3D9BC6F0.4080500 at cygnus-software.com:
> Then it should be much better to go:
>
> myList.reverse()
> while myList:
> # Do Something with the last element
> del myList[len(myList)-1]
>
> This changes it from O(n^2) to O(n), which could make it run thousands
> of times faster.
Ignoring any questions of speed, it may make the code somewhat clearer to
rewrite this as:
myList.reverse()
while myList:
element = myList.pop()
# Do Something with element
Alternatively, in many cases you can just avoid the removal of individual
items. For example if the list contains items to process, and during the
processing it is possible that more items are added:
while myList:
work, myList = myList, []
for item in work:
process(item)
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list