32

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.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222

2 Answers2

57

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.

wal-o-mat
  • 7,158
  • 7
  • 32
  • 41
  • hey. Is it possible without creating a list of combinations first? –  Nov 23 '11 at 13:26
  • Just using the itertools function gives you a plain iterator. If course you could iterate over that then and wait until your desired tuple arrives, counting the iterations. Or you could just find out the index of the first value in the first list, and the index of the second value in the second list and simply start to calculate :) – wal-o-mat Nov 23 '11 at 13:29
9

One way to do this:

  1. Find the first element of the pair your are looking for in the first list:

    p = (1, 4)
    i = a.index(p[0])
    
  2. Find the second element of the pair your are looking for in the second list:

    j = b.index(p[1])
    
  3. Compute the index in the product list:

    k = i * len(b) + j
    
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841