python all possible pairs of 2 list elements, and getting the index of that pair

user975135 picture user975135 · Nov 23, 2011 · Viewed 24.8k times · Source

let's say I have two lists:

a = list(1,2,3)
b = list(4,5,6)

So I can have 9 pairs of these list members:

(1,4)
(1,5)
(1,6)

(2,4)
(2,5)
(2,6)

(3,4)
(3,5)
(3,6)

Now, given two list members like above, can I find out the pair's index? Like (1,4) from above would be the 1st pair.

Answer

wal-o-mat picture wal-o-mat · Nov 23, 2011

And to complete the answer and stay in the example:

import itertools  

a = [1, 2, 3]
b = [4, 5, 6]
c = list(itertools.product(a, b))

idx = c.index((1,4))

But this will be the zero-based list index, so 0 instead of 1.