How can I combine each element of one list with each element of another?

Question:

Is there a compact way in Python to "multiply" two lists A and B such that every possible combination of elements has some operation applied to it, such that the resulting list has size A*B? I’ve only found answers in how to combine the nth element of each.

# arguments:
list_x = [a, b, c, d]
list_y = [1, 2, 3, 4]

# returns:
list_xy = [a1, a2, ..., d3, d4]
Asked By: frawgs

||

Answers:

I think you meant to ask the Cartesian product of the two lists.
itertools.product is the thing you are looking for

import itertools
list_xy = [i*j for i,j in itertools.product(list_x,list_y)]
Answered By: Himanshu Sheoran

if you want to do this only by the use of pure python (no import), you can do it like this:

# arguments:
list_x = ['a', 'b', 'c', 'd']
list_y = ['1', '2', '3', '4']
# returns:
list_xy = [a+b for a in list_x for b in list_y]
print(list_xy)

Output

['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3', 'c4', 'd1', 'd2', 'd3', 'd4']

you may use any other operation instead of a+b.

Answered By: Mahrad Hanaforoosh
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.