[Tutor] question about list

Liam Clarke cyresse at gmail.com
Fri Nov 12 01:26:07 CET 2004


Hi Lin, 

I  ran into this problem myself once, and I forgot how I fixed it. I
can, however, tell you what's going wrong -

a=['a','b','c','d','e','f','g']
b=[1,2,4]

for in in b:
del a[i]

Watch this 

for i in b:
   del a[1]

a becomes ['a','c','d','e','f','g']

next one around

del a[2]

a[2] is now 'd' !  so a becomes ['a','c','e','f','g']

del a[4]

a[4] is now 'g' so you are going to get -

a=['a','c','e','f']

So that's what's going wrong for you. 

I worked around this once by the following - but bear in mind that all
my workarounds are messy, and there will be a better way, which
hopefully someone will post shortly, because I'm curious also.

work-around - 

a=['a','b','c','d','e','f','g']
b=[1,2,4]

for i  in b:
   a[i]="XX"    <-- this makes a=['a','XX','XX','d','XX','f','g']

while a.count("XX"):  While the number of occurences of 'XX' in a are
above zero, do this...
      a.remove("XX")   Remove the first occurrence of 'XX' found

which gives you 

a=['a', 'd', 'f', 'g']


But like I said, there'll be an easier way.


Hope it helps, 

Liam Clarke





On Fri, 12 Nov 2004 07:24:50 +0800, Lin Jin <jinlin555 at msn.com> wrote:
> > i am new to python.i have a question about list.if i have two list:
> > a=[a,b,c,d,e,f,g]
> > b=[1,2,4]
> > and i want to remove the element of a using b,that is i want
> a=[a,d,f,g],my
> > code is like this:
> > >>>for i in b:
> > >>>    del a[i]
> >
> > but it is not working, it can't remove the correct items.what should i do
> 
> > to make it correct?thx
> 
> _________________________________________________________________
> 免费下载 MSN Explorer:   http://explorer.msn.com/lccn/
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.


More information about the Tutor mailing list