2

I have two lists [1,2,3] and [4,5,6]. I'd like to generate a list of all combinations as follows using itertools

ResultingList = [[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]

So far I've only investigated the itertools.combinations function which seems that it can only handle something like this:

list(itertools.combinations([1,2,3,4,5,6],2))

Which outputs an incorrect result. How can I generate ResultingList above?

Thanks

user32882
  • 5,094
  • 5
  • 43
  • 82

3 Answers3

6

Use product:

>>> from itertools import product
>>> list(product([1,2,3], [4,5,6]))
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

For general understaging:

As stated in the docs, product is the equivalent of: ((x,y) for x in A for y in B) where A and B are your input lists

Community
  • 1
  • 1
Or Duan
  • 13,142
  • 6
  • 60
  • 65
2

if you are not importing product from itertools , then you can use this way also

a=[1,2,3]
b=[4,5,6]
c=[]
for i in a:
    for j in b:
        c.append((i,j))
print c 
Arjun P P
  • 39
  • 1
  • 5
1

You can do simply :

print([(i,j) for i in a for j in b])

output:

[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]