Selecting elements from a list
David C. Fox
davidcfox at post.harvard.edu
Thu Sep 4 21:19:58 EDT 2003
Martin Christensen wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Howdy!
>
> Suppose I have a list A containing elements that I want to put into
> list B if they satisfy some property. The obvious way of doing it
> would be,
>
> B = []
> for i in A:
> if A.property():
> B.append(i)
>
> Now, list comprehensions, map() etc. can make a lot of list operations
> easier, but I haven't found a shorter, more elegant way of doing this.
> Have I missed something, or will I have to stick to my explicit loops?
>
> Martin
>
B = filter(lambda x: x.property(), A)
David
More information about the Python-list
mailing list