Search code examples
pythonpython-itertools

Create product of lists, concatenated, in python


import itertools
x = [[0,0],[1,1]]
list(itertools.product(x,x))

produces

[([0, 0], [0, 0]), ([0, 0], [1, 1]), ([1, 1], [0, 0]), ([1, 1], [1, 1])]

But I'm looking for something that produces

[[0, 0, 0, 0], [0, 0, 1, 1], [1, 1, 0, 0], [1, 1, 1, 1]]

Solution

  • In that case, you can easily do without using itertools, using list comprehension:

    x = [[0, 0], [1, 1]]
    output = [a + b for b in x for a in x]
    # [[0, 0, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1], [1, 1, 1, 1]]
    

    the equivalent without list comprehension would be:

    output = []
    for a in x:
        for b in x:
            output.append(a + b)
    print(output)