Selecting elements from a list

Duncan Smith buzzard at urubu.freeserve.co.uk
Thu Sep 4 18:46:09 EDT 2003


"Martin Christensen" <knightsofspamalot-factotum at gvdnet.dk> wrote in message
news:87y8x4w6ym.fsf at gvdnet.dk...
> -----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
>

Is this the sort of thing you mean?

>>> A = [0, 1, 2, 'four', 'five', 6.0]
>>> [x for x in A if isinstance(x, str)]
['four', 'five']
>>>

Duncan






More information about the Python-list mailing list