Newbie question about list method remove

Robert Brewer fumanchu at amor.org
Wed May 5 19:17:33 EDT 2004


Sean Berry wrote:
> >>> li2 =['this.txt', 'that.txt', 'April04', 'more.txt']
> >>> for item in li2:
>             if ".txt" in item:
>                 li2.remove("%s" %item)
> >>> li2
> ['that.txt', 'April04']
> 
> I would think that 'that.txt' would be removed as well.  
> Where am I wrong?

In general, you can't modify a list while you iterate over it. Read the
Warning on the bottom of the page at:
http://www.python.org/doc/current/ref/for.html

Then search the archives of c.l.p. for Many Ways To Do It Differently.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list