List of lists

Marc Boeren M.Boeren at
Wed Nov 19 13:18:35 CET 2003

> I was wondering if anyone knows a short way to do the following..
> I have 2 lists of
> [('a','b','c'),('k','-','l'),('1','2','3')]
> [('a','b','c'),('k','-','x'),('1','4','3')]
> I want to comapre the two lists of lists and count the number of 
> times the sublists match. In the above example its 1

Anytime you need to do something on corresponding items in two lists, you
should think of zip(), as this binds the matching elements together.
Look at:

>>> a = [('a','b','c'),('k','-','l'),('1','2','3')]
>>> b = [('a','b','c'),('k','-','x'),('1','4','3')]
>>> [aa==bb for aa, bb in zip(a,b)]
[True, False, False]
>>> sum([aa==bb for aa, bb in zip(a,b)])

the list-comprehension [aa==bb for aa, bb in zip(a,b)] can be used to count
how many items matched, but is also useful to determine exactly which items

Cheerio, Marc.

More information about the Python-list mailing list