Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Newbie question about list method remove

Reply
Thread Tools

Newbie question about list method remove

 
 
Sean Berry
Guest
Posts: n/a
 
      05-05-2004
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


 
Reply With Quote
 
 
 
 
news-server.sdd.hp.com
Guest
Posts: n/a
 
      05-06-2004
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" <(E-Mail Removed)> 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
>
>



 
Reply With Quote
 
 
 
 
Larry Bates
Guest
Posts: n/a
 
      05-06-2004
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" <(E-Mail Removed)> 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
>
>



 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Problem with list.remove() method Alvaro Combo Python 7 11-21-2012 12:08 AM
remove a list from a list Rares Vernica Python 1 11-20-2006 07:32 PM
Re: remove a list from a list Rares Vernica Python 5 11-17-2006 11:42 PM
Re: remove a list from a list Rares Vernica Python 4 11-17-2006 09:22 PM
How to remove items from add/remove list please Caractucus Potts Computer Support 5 07-03-2005 10:31 PM



Advertisments