The pythonic way to generate pairs

Dima picture Dima · Jun 27, 2011 · Viewed 52.7k times · Source

I want something like code below, but "pythonic" style or using standard library:

def combinations(a,b):
    for i in a:
        for j in b:
             yield(i,j)

Answer

Sven Marnach picture Sven Marnach · Jun 27, 2011

These are not really "combinations" in the sense of combinatorics, these are rather elements from the cartesian product of a and b. The function in the standard library to generate these pairs is itertools.product():

for i, j in itertools.product(a, b):
    # whatever