From: Ype K. <yk...@xs...> - 2001-09-12 18:37:55
|
>Hi, > >why does the following not work: > >a = [1, 2] >for i in a: > a.remove(i) > > >The loop exits after the first iteration leaving a = [2] > >How do I get around this problem? Iterating over a list that is being modified results in undefined behaviour. A better way is: for i in a[:]: # iterate over a copy a.remove(i) # remove from original The problem with this is that it still needs to access each element in the list (at least twice). When you need to remove some of the elements in a list you could also use list comprehensions, but these always create a new list: a = [i for i in a if not someRemoveCondition(i)] To empty a list in a single operation you can also: a[:] = [] # modify in place to become an empty list. (A) or a = [] # change to refer to a new empty list object. (B) or, preferably: del a[:] # modify in place deleting all entries (C) The last variant does not create a new object, which can make a measurable difference for garbage collection in case it avoids creating a lot of them. This technique is also known as reusing existing objects. I have never measured the difference between (A) and the other two, but (C) is definitely faster than (B) in Jython. It is probably faster in CPython, too. > >Any help appreciated, >Kevin My pleasure, Ype |