2

let's say i have 2 lists like below:

list1=[[1],[2],[3]]
list2=[[4],[5]]

What i would like to do is cross product between the list items in these two lists.In this example the result would be :

    result_list=[[1,4],[1,5],[2,4],[2,5],[3,4],[3,5]]

How could this be done using python ? i have searched online for a bit but i can't find a solution and i've been stuck.Any help would be very welcome.

Thanks in advance!!

arxidaras
  • 21
  • 2
  • You may think about [accepting an answer](https://stackoverflow.com/help/someone-answers) to reward those how helped you, or at least comment to explain what's missing ;) – azro Mar 27 '21 at 11:42

4 Answers4

7

You can try itertools.product

from itertools import product
list1=[[1],[2],[3]]
list2=[[4],[5]]

output = [[x[0][0], x[1][0]] for x in product(list1, list2)]

print(output)
[[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
Epsi95
  • 8,832
  • 1
  • 16
  • 34
3

That is cartesian product, but as you have 2-level lists as input, you need a little trick to get the result

  • flatten the result after product

    from itertools import product, chain
    res = [list(chain(*r)) for r in product(list1, list2)]
    
  • flatten the input list before product

    res = list(product(chain(*list1), chain(*list2)))
    

If you have 1-level list, it's just

list1 = [1, 2, 3]
list2 = [4, 5]
res = list(product(list1, list2))
print(res)  # [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
azro
  • 53,056
  • 7
  • 34
  • 70
1
list1=[[1],[2],[3]]
list2=[[4],[5]]
a =[]
for i in list1:
    for j in list2:
        a.append([i[0],j[0]])
print(a)
[[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
Zeinab Mardi
  • 133
  • 1
  • 5
1

From itertools, product will produce the required pairings but the output will be tuples of on-item lists. You can use chain.from_iterable to combine those lists and map the result to lists efficiently:

from itertools import product,chain
result_list = [*map(list,map(chain.from_iterable,product(list1,list2)))]

[[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
Alain T.
  • 40,517
  • 4
  • 31
  • 51