Index of duplicate items between two list in python

I have two list A and B. I have to print those elements index number(index number+1) of list A ,which elements also exist in list B. For Every elements of B list will print in new line.

Len(B) <=100

A = [['a'], ['a'], ['b'], ['a'], ['b']]
B =  [['a'], ['b']]

I have done so far:

for i,x in enumerate(A):
        if B[0] == x:
            print(i+1,end=" ")

My output:

1 2 4 

Expected Output:

1 2 4
3 5

How can i fix this?

You could make a outer loop that iterates over the elements of B

you have 2D arrays, (matrixes/ array of arrays), is that what you meant?
a list would be:
A = [‘a’, ‘b’]
and you have (array of arrays)
A = [[‘a’], [‘b’]]
do you see the difference?
and then you can loop thorough A and just check “if A[i] in B”.
does this make sense?

Can you please , give an example?

Did you mean this:

A = ['a', 'a', 'b', 'a', 'b']
B =  ['a', 'b']


for i in (A):
    if i in B:
        print(A.index(i)+1,end=" ")

But Output is:

1 1 3 1 3

I need ,

1 2 4
3 5

Every time it catches first 'a' element of list A :frowning:

ok, i see. so it is just an array and not an array of arrays. good. so now it looks like you need to keep track of the position of the elements from B in A. First you need to keep track of things you find, so create C which will actually be an array of arrays. For each element in B you will create row in C and add every index from A to that row. so in the end your matrix C will look like:

[[1], [2], [4]]
[[3], [5]]

Also suggest to reverse the logic and start going through B first. While going through the first element in B, go through every element in A and if B[i] == A[j] add a new element in C[i].
how is that? I’m trying to describe the logic instead of writing code for you, but i can do that as well, if you prefer.

1 Like

I understand,but cannot apply logic in code.Can you please give the code,then i will try to understand what’s going on :disappointed:

there are multiple approaches obviously, it all depends on the sophistication of loops and python in general. here’s a simple and elegant solution i ended up with

a = ['a', 'a', 'b', 'a', 'b']
b = ['a', 'b']

for index_b, item_b in enumerate(b):
    for index_a, item_a in enumerate(a):
        if item_b == item_a:
            print(index_a + 1, end=" ")
    print('')

you don’t have to use ‘enumerate’ if you are not familiar. you can as easily use ‘for (var i = 0; i < b.length; i++):’ . I also didn’t use any C array to save things and just printed out the result. if you need to use the result later, you need to save it somewhere.

1 Like