frazman
frazman

Reputation: 33303

Find the index of top most element common in two lists

Say, I have two lists

  retrieved = ["foo", "bar", "baz", "foobar"]
  relevant = [ "foobar", "baz"]

What the pythonic way to find the first element present in retrieved that is also "relevant"

So in the example above.. since "baz" is the first relevant object retrieved. It should return 2, corresponding to the index 2 in retrieved.

Thanks

Upvotes: 1

Views: 42

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 61063

As a for loop

for i, item in enumerate(retrieved):
    if item in relevant:
        print(i)
        break

As a generator

print(next(i for i, item in enumerate(retrieved) if item in relevant))

Read more on enumerate

Upvotes: 2

Related Questions