Selecting elements from a list

Jeremy Jones zanesdad at bellsouth.net
Thu Sep 4 20:14:38 EDT 2003


* Duncan Smith (buzzard at urubu.freeserve.co.uk) wrote:
> 
> "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']
> >>>
> 

filter() works well as well:


>>> foo
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> filter(lambda x: x > 4, foo)
[5, 6, 7, 8, 9]

Jeremy Jones





More information about the Python-list mailing list