0

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?

1
  • 1
    print([i for i, v in enumerate(l1) if v in set(l2)]) Commented Apr 13, 2020 at 11:00

2 Answers 2

0

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)]
Sign up to request clarification or add additional context in comments.

1 Comment

if you use a set for l2 the complexity is O(n).
0

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.