Mailing List Archive

filtering a list
I'm uncertain as to whether this kind of construct is well formed

R is a list of instances

for i in R:
if i.id%2: del R[R.index(i)]

or is it better (assuming R holds the only references to the instances)
to do

R=filter((lambda x: x.id%2),R)
--
Robin Becker
filtering a list [ In reply to ]
In article <yILNBDAxDVw3EwSE@jessikat.demon.co.uk>,
robin@jessikat.demon.co.uk says...
[posted and emailed]

>I'm uncertain as to whether this kind of construct is well formed
>R is a list of instances
>
>for i in R:
> if i.id%2: del R[R.index(i)]

I believe that modifying the for-list is unwise since i will never be
pointed at item after that deleted when its reference is shifted down
into now empty slot. IE, 'for' creates internal index but not internal
copy.

>or is it better (assuming R holds the only references to the instances)
>to do
>
>R=filter((lambda x: x.id%2),R)
>--
>Robin Becker

In this case yes.
Terry J. Reedy