for i in list - change a list inside a for loop?

Erik Max Francis max at alcyone.com
Mon Mar 3 21:30:51 CET 2003


dsavitsk wrote:

> why not ...
> 
> while 1:
>     try:
>         x.remove('C')
>     except:
>         break
> 
> which might not be as fast [1], but is very readable.
> 
> [1] I have no idea about this, but it seems that it is going to loop
> less
> times than the other options.

It's O(n) through each loop, so if there may be a lot of elements you
want to remove from the list, it can degenerate to O(n^2) [O(m n) with m
~ n].  Whereas the expilcit iterate-and-filter method is always O(n),
regardless of the frequency of the unwanted element.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Death to all fanatics!
\__/ Malaclypse the Younger
    CSBuddy / http://www.alcyone.com/pyos/csbuddy/
 A Counter-Strike server log file monitor in Python.




More information about the Python-list mailing list