How to make couple for elements from two list (different size) in Python?

I need to make couple for elements from two lists (two lists are different size)
Ex:

x = ([3,2], [4,6,-8])
y = ([-5,1,4], [13,9], [7,5,-1,10])

Result:

new_list = ([3, -5], [3, 1], [3, 4], [3, 13], [3, 9], [3, 7], [3, 5], [3, -1],[3, 10], [2, -5], [2, 1] ......<sorry, there're too many>.... [-8, 5], [-8, -1], [-8, 10])

Thanks for suppost!

>Solution :

In two steps, 1) flatten your list of lists, 2) itertools.product

Flatten your list of lists:
How to make a flat list out of a list of lists

flat_list = [item for sublist in t for item in sublist]

Use itertools to create the product of the two lists.

itertools.product(x, y)

Example from OP:

x = ([3,2], [4,6,-8])
y = ([-5,1,4], [13,9], [7,5,-1,10])
x_flat = [item for sublist in x for item in sublist]
y_flat = [item for sublist in y for item in sublist]
list(itertools.product(x_flat, y_flat))

result:

[(3, -5), (3, 1), (3, 4), (3, 13), (3, 9), (3, 7), (3, 5), (3, -1), (3, 10), (2, -5), (2, 1), (2, 4), (2, 13), (2, 9), (2, 7), (2, 5), (2, -1), (2, 10), (4, -5), (4, 1), (4, 4), (4, 13), (4, 9), (4, 7), (4, 5), (4, -1), (4, 10), (6, -5), (6, 1), (6, 4), (6, 13), (6, 9), (6, 7), (6, 5), (6, -1), (6, 10), (-8, -5), (-8, 1), (-8, 4), (-8, 13), (-8, 9), (-8, 7), (-8, 5), (-8, -1), (-8, 10)]

Leave a Reply