nested looping

Matimus mccredie at
Thu Apr 9 00:07:04 CEST 2009

On Apr 8, 2:15 pm, PK <superp... at> wrote:
> So I'm trying to see whats the cleanest way to do this:
> I have a
> checklist = [ax, bx, by, cy  ..] (a combination of a,b,c with x and y,
> either both on one)
> allist = [a,b,c,....]
> xlist = [x, y, ..]
> now I wanna loop through alist and xlist and see if the combination
> exists in checklist
> so something like,
> for alpha in alist:
>     for xy in xlist:
>         if alpha+xy not in checklist:
>             missing.append(alpha)
> now the problem is I want to include alpha in missing list only if
> none of the combinations from xlist with alpha are in checklist.
> The above will exclude the possibility where ax doesn't exist but ay
> or az does exist.
> Hope There is a cleaner way to accomplish this.
> Thanks in advance,
> PK

That code doesn't look too bad. It is fairly readable. There are
several ways to accomplish this though. If you aren't interested in
duplicate values or order then sets would be a good option.

something like this:

missing = set(alpha + xy for alpha in alist for xy in xlist).difference

if you are using 2.6 you could also make use of the product generator
in itertools:

from itertools import product
missing = set(''.join(p) for p in product(alist, xlist)).difference

If you could adapt your code to use tuples instead of strings you
could do it like this:

missing = set(product(alist, xlist)).difference(checklist)


More information about the Python-list mailing list