Karnivaurus
Karnivaurus

Reputation: 24151

Finding the indices of the values of one list in another list

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

Upvotes: 3

Views: 588

Answers (1)

csiu
csiu

Reputation: 3279

Here is one way to do it:

z = [y.index(i) for i in x]

Upvotes: 6

Related Questions