list.pop([i]) and list.remove(x) w/ for loops
wjk
wjk at wjk.mv.com
Thu Jun 29 20:01:57 EDT 2000
Hi -- I usually use pop when iterating a list in reverse:
after i make a copy of it
y=[1,2,3,4,3,5,6]
copy=[:]
for x in range(len(y)-1,-1,-1):
if y[x] == 3:
y.pop(x)
I am unsure of list.remove(something) since I think it
removes the 1st occurance in a list thus iterating in
reverse might present a problem there as well.
other alternative:
lista = [1,2,3]
listb = [1,2,3,1,2,3,4,5,1,2,3]
for x in lista:
try:
while listb.index(x):
listb.remove(x)
except:
pass
(kinda ugly huh?)
never thought of using "del listb[x]" that I will add somewhere
in my head..
Moshe Zadka wrote:
> On 28 Jun 2000, David White wrote:
>
> > I was getting some unexpected behavior when using list.remove(x), wondering if
> > someone can tell me what's going on.
> >
> > I have a list of 2 kinds of objects, such as [a, a, b, b, a, b]. I wan't to
> > delete all the a objects out of the list while preserving the order of the b
> > objects. My code looks like this:
> >
> > for o in olist:
> > if (o.type == a):
> > olist.remove(o)
>
> Short answer: never ever modify a list you're iterating on. Make a copy
> first.
>
> running-faster-is-pointless-if-you-get-the-wrong-answer-ly y'rs, Z.
>
> --
> Moshe Zadka <moshez at math.huji.ac.il>
> http://www.oreilly.com/news/prescod_0300.html
> http://www.linux.org.il -- we put the penguin in .com
More information about the Python-list
mailing list