Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Newbie question about list method remove (http://www.velocityreviews.com/forums/t330627-newbie-question-about-list-method-remove.html)

Sean Berry 05-05-2004 11:13 PM

Newbie question about list method remove
 
Why is this:

>>> 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?

TIA



news-server.sdd.hp.com 05-06-2004 12:03 AM

Re: Newbie question about list method remove
 
Try this,

> >>> li2 =['this.txt', 'that.txt', 'April04', 'more.txt']
> >>> for item in li2[:]: #Make a copy of the list

> if ".txt" in item:
> li2.remove("%s" %item)
> >>> li2

> ['that.txt', 'April04']


Mike

"Sean Berry" <sean_berry@cox.net> wrote in message
news:myemc.69648$Jy3.5301@fed1read03...
> Why is this:
>
> >>> 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?
>
> TIA
>
>




Larry Bates 05-06-2004 12:32 AM

Re: Newbie question about list method remove
 
In Python you must think "differently" than in
other programming languages.

li2=[f for f in li2 if not f.endswith('.txt')]

for your specific example or in Python 2.2 and earlier

li2=[f for f in li2 if f.count('.txt') == 0]

for the more general .txt ANYWHERE in the string

or in Python 2.3

li2=[f for f in li2 if not '.txt' in f]


Larry Bates
Syscon, Inc.

"Sean Berry" <sean_berry@cox.net> wrote in message
news:myemc.69648$Jy3.5301@fed1read03...
> Why is this:
>
> >>> 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?
>
> TIA
>
>





All times are GMT. The time now is 01:32 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.