[Tutor] Comparing two lists

Steven D'Aprano steve at pearwood.info
Fri Sep 17 03:40:49 CEST 2010


On Fri, 17 Sep 2010 04:27:28 am Michael Powe wrote:
> Hello,
>
> I have two lists.
>
> alist = ['label', 'guid']
>
> blist = ['column0label', 'column1label', 'dimension0guid',
> 'description', 'columnid']
>
> I want to iterate over blist and extract the items that match my
> substrings in alist; 

Presumably you want to get:

clist = ['column0label', 'column1label', 'dimension0guid', 'columnid']


> alternatively, throw out the items that aren't 
> in alist (but, I've had bad experiences removing items from lists "in
> place," so I tend toward the "copy" motif.)

That's almost always the best approach in Python.


> In real life, blist column entries could have embedded column numbers
> from 0 to 19.
>
> I can do this with excrutiatingly painful 'for' loops.  Looking for
> something more efficient and elegant.

Why would they be painful, let alone excruciatingly so?

clist = []
for b in blist:
    for a in alist:
        if a in b:
            clist.append(b)
            break

Okay, it's not elegant but it is concise as far as number of operations 
performed, and six lines of code isn't really that bad. There shouldn't 
be anything painful about it. It's simple to read and understand, and 
short enough that you could use it in place if necessary, although I'd 
wrap it in a function.

You can get rid of the inner for-loop:

clist = []
for b in blist:
    if any(a in b for a in alist):
        clist.append(b)

which then makes the list comp form obvious:

clist = [b for b in blist if any(a in b for a in alist)]



-- 
Steven D'Aprano


More information about the Tutor mailing list