beginner, idiomatic python

Paul Rubin http
Mon Aug 27 06:11:03 CEST 2007

"bambam" <david at asdf.asdf> writes:
> Is it safe to write
> A = [x for x in A if x in U]
> or is that undefined? I understand that the slice operation
> can be used to make a temporary copy, so I could write
> A=[x for x in A[:] if x in U]
> but I've just copied that without any understanding.

You get a temporary copy either way; note you're going to linearly
search U on every pass.  Maybe you want:

   SU = set(u)
   A = [a for x in A if x in SU]

or possibly

   A = list(set(A) & set(U))

which will remove duplicate elements from A and not necessarily keep
them in the same order, but is likely to be fastest of the bunch.

More information about the Python-list mailing list