Reputation: 46
I have two lists:
l1 = [1, 46, 8, 9, 4, 76, 797, 342, 3, 5, 67, 42, 87]
l2 = [42, 34, 5, 78, 8, 9, 4]
I want to find out the index of l1
that have matches in l2
.
Can anyone help me out?
Upvotes: 0
Views: 79
Reputation: 1842
The problem with enumerate and set is that it does not keep the order, here's a code that does this:
print([l1.index(k) for k in l2 if k in l1])
Upvotes: 0
Reputation: 3531
Naive method:
for i in range(len(l1)):
try:
if l1[i] in l2:
print(i)
except ValueError:
pass
You can also use a oneliner, which is more efficient because the lookup in a set is done in constant time, credits to @Matthias for pointing that out:
[i for i, v in enumerate(l1) if v in set(l2)]
Upvotes: 0