-2

Let's say I have two lists a = [1,2,3,4] b = [5,9,1,2]

and I want to get the indices of every element in list b when an element of list a is in there. In this example, the result should be a list c containing all indices in b c = [2,3] 1 in list a is on index 2 in b 2 in list a is on index 3 in b

Thanks in advance!!

bloobi
  • 1

5 Answers5

1
[index for (index, item) in enumerate(b) if item in a]

output

[2, 3]
Yaset Arfat
  • 106
  • 1
0

Use this:

c = [b.index(x) for x in a if x in a and x in b]
c

Output:

[2, 3]
Prakash Dahal
  • 4,388
  • 2
  • 11
  • 25
0

I would solve that this way:

a = [1, 2, 3, 4]
b = [5, 9, 1, 2]
b_d = {b[i]: i for i in range(len(b))}
result = [b_d[v] for v in a if v in b_d]

print(result)
Captain Trojan
  • 2,800
  • 1
  • 11
  • 28
0

Using a set will make the inclusion check faster:

set_a = set(a)
c = [i for i, x in enumerate(b) if x in set_a]
Will Da Silva
  • 6,386
  • 2
  • 27
  • 52
0

You could simply iterate over the first list, then check if the item is inside the second list, if yes then append the index to your new list c:

a = [1,2,3,4]
b = [5,9,1,2]
c = []

for item in list_a:
    if item in list_b:
        c.append(list_b.index(item))

print(c)

Or use a list comprehension:

[list_b.index(item) for item in list_a if item in list_b]
Aru
  • 352
  • 1
  • 11