'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 1:[1]

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)

Solution 2:[2]

itertools.product is giving you that answer, you just have to concatenate the lists

[a + b for a, b in [([0, 0], [0, 0]), ([0, 0], [1, 1]), ([1, 1], [0, 0]), ([1, 1], [1, 1])]]
# [[0, 0, 0, 0], [0, 0, 1, 1], [1, 1, 0, 0], [1, 1, 1, 1]]

Solution 3:[3]

You can use np.reshape if you are considering numpy array.

np.reshape(list(itertools.product(x,x)),(4,4))
Out[28]: 
array([[0, 0, 0, 0],
       [0, 0, 1, 1],
       [1, 1, 0, 0],
       [1, 1, 1, 1]])

Solution 4:[4]

You can use map and lamda then combine two array that came from itertools.product like below:

import itertools
x = [[0,0],[1,1]]
list(map(lambda x: x[0]+x[1] , itertools.product(x,x)))

Output:

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

Extended version:

from itertools import chain
list(map(lambda x: list(chain(*x)) , itertools.product(x, repeat=4)))  
# itertools.product(x, repeat=4) <=> itertools.product(x,x,x,x)

Output:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Kraigolas
Solution 3 Kevin Choon Liang Yew
Solution 4