This is trivial with list comprehension, and is practically covered on the list comprehension examples for iterating over two lists.
In the first instance, you need to iterate over each list:
[(x,y) for x in a for y in b]
This gives every pair for each list ordered by the elements of a
with b
(notive the order of the elements below).
[(1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (1, 12), (2, 7), (2, 8),
(2, 9), (2, 10), (2, 11), (2, 12), (3, 7), (3, 8), (3, 9), (3, 10),
(3, 11), (3, 12), (4, 7), (4, 8), (4, 9), (4, 10), (4, 11), (4, 12),
(5, 7), (5, 8), (5, 9), (5, 10), (5, 11), (5, 12), (6, 7), (6, 8),
(6, 9), (6, 10), (6, 11), (6, 12)
]
Then apply a filter at the end to restrict the list:
>>> a = [1,2,3,4,5,6]
>>> b = [7,8,9,10,11,12]
>>> [(x,y) for x in a for y in b if x+y==12]
[(1, 11), (2, 10), (3, 9), (4, 8), (5, 7)]
This can be created as a generator, when elements are created as needed, instead of creating and storing the whole list in memory if a
and b
are rather large.
Like so (note the round brackets instead of square brackets):
>>> ((x,y) for x in a for y in b)
<generator object <genexpr> at 0x7f12e1bfef00>