All possible variants of zip in Python

Question:

For example, I have a code looks like this:

a = [1, 2]
b = [4, 5]

How can I get something like this:

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

Like function zip does, but with all possible variants. Or can’t I?

Asked By: alexvassel

||

Answers:

You want itertools.product:

>>> import itertools
>>> a = [1,2]
>>> b = [4,5]
>>> list(itertools.product(a,b))
[(1, 4), (1, 5), (2, 4), (2, 5)]
Answered By: DSM

If you’re interested only in the result, then itertools.product is what you need (+1 to @DSM for this). However, if you’re interested in the algorithm that generates something like this, it’s called recursive descent. The algorithm, in this case, would run as follows (I’m just going to print the results here for clarity):

def product(L, tmp=None):
    if tmp is None:
        tmp = []
    if L==[]:
        print tmp
    else:
        for i in L[0]:
            product(L[1:], tmp+[i])

Thus,

>>> product([[1,2], [4,5]])
[1, 4]
[1, 5]
[2, 4]
[2, 5]

Hope this helps

Answered By: inspectorG4dget

Don’t overlook the obvious:

out = []
for a in [1, 2]:
    for b in [4, 5]:
        out.append((a, b))

or list comprehensions:

a = [1, 2]
b = [4, 5]
out = [(x, y) for x in a for y in b]

Both produce out == [(1, 4), (1, 5), (2, 4), (2, 5)]

Answered By: endolith

You can do this nicely with list comprehension, or better yet with a generator expression if you just need to iterate through the combinations.

Here’s it is using list comprehension:

a = [1, 2]
b = [4, 5]

[(i, j) for i in a for j in b]

And here with a generator expression:

for pair in ((i, j) for i in a for j in b):
    print(pair)
Answered By: Nir Yungster
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.