3

I have two Python lists of integers: x, and y. All elements of x appear somewhere in y, and only once. For each element of x, I want to know the index of the corresponding value in y. I then want to set these indices to a list z.

The code below works as I have just described. However, it seems a little clumsy for a task which I suspect may have a more elegant solution in just a couple of lines or so. Therefore, my question is, what is the least number of lines in which the following code can be rewritten?

z = [0 for i in range(len(x))]
for i, j in enumerate(x):
    for k, l in enumerate(y):
        if j==l:
            z[i] = k
            break
Karnivaurus
  • 22,823
  • 57
  • 147
  • 247

1 Answers1

6

Here is one way to do it:

z = [y.index(i) for i in x]
csiu
  • 3,159
  • 2
  • 24
  • 26
  • That's the way to do it. – Dan D. Oct 26 '14 at 04:51
  • 1
    Note that while this may not be an issue in practice for small lists, this has quadratic behaviour and so will be slow for large ones. (You wind up scanning `len(x)` times through `y`, when really you only need to do it once.) – DSM Oct 26 '14 at 05:03