Why doesnt my cartesian product function work?

Viewed 84

Consider the following function, whose output is supposed to be the cartesian product of a sequence of iterables:

def cart(*iterables):
    out = ((e,) for e in iterables[0])
    for iterable in iterables[1:]:
        out = (e1 + (e2,) for e1 in out for e2 in iterable)
    return out

Works fine when generator comprehensions are replaced with list comprehensions. Also works when there are only 2 iterables. But when I try

print(list(cart([1, 2, 3], 'ab', [4, 5])))

I get

[(1, 4, 4), (1, 4, 5), (1, 5, 4), (1, 5, 5),
 (2, 4, 4), (2, 4, 5), (2, 5, 4), (2, 5, 5),
 (3, 4, 4), (3, 4, 5), (3, 5, 4), (3, 5, 5)]

Why this and not the cartesian product?

1 Answers
Related