how to delete multiple elements from a list

etsang at my-deja.com etsang at my-deja.com
Wed Nov 15 17:06:20 EST 2000


Hi, I have another question regarding this. How about Y continas two
batch of positions, with each in consecutive order?

E.g. List X = [0,1,2,3,4,5,6,7,8]
List Y =  [1,2,3,6,7,8]
when List Y is in decedning order: [8,7,6,3,2,1]
I use a loop like:
for x in ListY:
  try:
    ListX.del(x)
  except:
    IndexError

when I use a for loop to delete elements at position specififed by List
Y from List X.
After it deleted elements 1,2,3, there are no elements at 8,7,6
anymore. So there is somekind of index error.

It only works when List Y is in consecutive order e.g. if List Y is
somehting like [1,2,3,4,5]

How can I make this works in all cases:
1. when all elements in Y are consecutive:
2. when some elements in Y are consecutive
3. when Y contains elements consecutive in more than one place?

No element in Y is repeated.
Can someone kindly supply the code??
Thansk

In article <tRmQ5.27$OC.6765 at typhoon.aracnet.com>,
  "Daniel Klein" <DanielK at aracnet.com> wrote:
> You need to iterate thru the list from the end, ie process the last
element,
> then next to the last, etc.
>
> Dan
>
> <etsang at my-deja.com> wrote in message news:8usjl6
$vea$1 at nnrp1.deja.com...
> > Hi,
> >
> > I have a List X with N number of items in it. I have another List Y
> > which contains the postion of the elements to be deleted from List
X.
> > I cannot do a for loop to delete that because for each iteration,
List
> > X will be changed and there will be sliperage.
> >
> > How can I delete all the items as specified by the positions in Y at
> > one time? Also both List X and List Y are known in run time only.
> > Thanks
> >
> >
> > Sent via Deja.com http://www.deja.com/
> > Before you buy.
>
>


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list