pythonset

Compute cartesian product of two lists without elements at same index


I have two lists with the same length, say 3.

A=[1,2,3]
B=[4,5,6]

I want to get Cartesian product of the two, but the element at the same position shouldn't be count i.e. :

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

How shall I do that?


Solution

  • You can nearly directly jot down your 'refined' carthesian product:

     ((a[i], b[j]) 
          for i in range(len(a))
          for j in range(len(b))
          if i != j)