zip
is your friend:
good_vals = [(aa, bb) for aa, bb in zip(a, b) if aa + bb == 12]
EDIT
Since it looks like you want to do an all-to-all comparison, then you'll need a nested loop -- either explicit or implied. Here are some options:
# itertools.product
[tup for tup in it.product(a, b) if sum(tup) == 12]
# nested list-comp
[(aa, bb) for aa in a for bb in b if aa + bb == 12]
# good ole' fashioned loop:
result = []
for aa in a:
for bb in b:
if aa + bb == 12:
result.append((aa, bb))
Some might wonder why I include the last option ... Indeed, it is much more verbose and typically less efficient than the other two. However, in some cases, you might be able to continue the outer loop without doing the inner loop at all ... e.g. if aa > 12
and you know that bb
is always positive due to some constraint on the problem. If that's the case, then you might actually get some performance benefit from the slightly better algorithm (of course, the normal suggestions apply: timeit
with real data to know if it's worth the extra lines of code).