Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find index of element of one list in another list which includes the same elements?

Tags:

python

list

I am trying to code in python this simple task (part of a bigger project):

I have two lists where the first one, let's say A = [1, 2, 3, 4, 5, 6] is sorted and the second one, let's say B = [3, 4, 1, 6, 2, 5] is not sorted. What I want to achieve is to obtain the value of the index for each element of the sorted list A in list B. For example, I want to come with the result of index i = 3 when I search for the element A[5] = 6. I have implemented in the simple way as follows:

for i in range(6):
    for j in range(6):
        if A[i] == B[j]:
            index = j

I would want to come up with a way which reduces it to only one loop instead of these two nested for loops.

like image 521
Teo Protoulis Avatar asked Dec 06 '25 18:12

Teo Protoulis


1 Answers

If you know that all the values in B are unique, one way would be to create a dictionary that maps the values in B to their indices.

b_dict = {}
for i, b in enumerate(B):
    b_dict[b] = i

Then, loop over A and get all the values from b_dict.

a_indices = [b_dict[a] for a in A]

With your lists, we get

A: [1, 2, 3, 4, 5, 6]
B: [3, 4, 1, 6, 2, 5]
a_indices: [2, 4, 0, 1, 5, 3]

This solution is O(n) as opposed to the others, which are O(n^2), and will therefore be much faster on large lists.

like image 142
Pranav Hosangadi Avatar answered Dec 08 '25 06:12

Pranav Hosangadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!