Newbie question about list method remove

N

news-server.sdd.hp.com

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)['that.txt', 'April04']

Mike

Sean Berry said:
Why is this:
li2 =['this.txt', 'that.txt', 'April04', 'more.txt']
for item in li2:
if ".txt" in item:
li2.remove("%s" %item)['that.txt', 'April04']

I would think that 'that.txt' would be removed as well. Where am I wrong?

TIA
 
L

Larry Bates

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 said:
Why is this:
li2 =['this.txt', 'that.txt', 'April04', 'more.txt']
for item in li2:
if ".txt" in item:
li2.remove("%s" %item)['that.txt', 'April04']

I would think that 'that.txt' would be removed as well. Where am I wrong?

TIA
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top