How to del item of a list in loop?

skull skullw at sina.com.cn
Sat Jan 15 21:07:27 EST 2005


Reinhold Birkenfeld <reinhold-birkenfeld-nospam at wolke7.net> writes:

>> Quick solution:
>> 
>> for i in lst[:]
>> 
>> iterates over a copy.
>
> Addition: In Py2.4, I can't find a problem with
>
> for i in reversed(lst)
>
> Any objections?
>
> Reinhold

I just downloaded py2.4, and made a test using reversed.
it sure be no problem, I thought maybe the reversed holded a copy of list,
and eventually iterated through the copy.
but the truth is not as I thought so:

import sys

class Test:
    pass

lst = [Test(),Test(),Test()]

E1: for i in lst[:]:
E2: for i in reversed(lst):
    print sys.getrefcount(i)

###################
E1 outputs:
4
4
4

E2 outputs:
3
3
3

It looks that the reversed does not make a copy of list in contrast with lst[:].
so should we regard: reversed is faster than lst[:]?
I do not have any idea about why it is.

- skull



More information about the Python-list mailing list