-1

I'm trying to obtain indexes of one list based on elements of another list.

Let's say I have:

list1 = [1, 2]
list2 = [1, 2, 2, 3]

I want to obtain indexes of list2 that match elements from list1:

>>> [0, 1, 2]

Is there any one liner that can do it? Thank you for any suggestions.

EDIT: Current multiple line solution:

list1 = [1, 2]
list2 = [1, 2, 2, 3]
matched = []

for i, e in enumerate(list1):
    for j, f in enumerate(list2):
        if e == f:
            matched.append(j)

>>> [0, 1, 2]
matt
  • 1
  • 3
  • 1
    So how would you do this with more that one line? – quamrana Jun 30 '21 at 13:34
  • I don't know that yet. I am open to any suggestions but one liner would be the best. – matt Jun 30 '21 at 13:35
  • 2
    I'm sorry, but stackoverflow is not a code writing service. You should do some research for that and when you get stuck, that's the time to ask a specific question. – quamrana Jun 30 '21 at 13:36
  • 1
    If you want a one liner, use a list comprehension, with the logic you would use with multiline solution. – May.D Jun 30 '21 at 13:36
  • "Code writing service" - that's why I wrote "any suggestions" like in which direction to go. I tried for some time and failed, that's why I asked. – matt Jun 30 '21 at 13:41
  • It is all not intended to replace existing tutorials or documentation — so clearly you have some more studying to do. – martineau Jun 30 '21 at 13:42
  • 1
    I think you will not understand these one-liner solutions if you do not know how to write a "more than one line" code. – Ram Jun 30 '21 at 13:51
  • Does this answer your question? [Find the indices at which any element of one list occurs in another](https://stackoverflow.com/q/29452735/6045800) – Tomerikoo Jul 01 '21 at 14:05

3 Answers3

0

Try:

>>> [i for i, x in enumerate(list2) if x in list1]
[0, 1, 2]
not_speshal
  • 22,093
  • 2
  • 15
  • 30
0

how about something like this:

print([i for i in range(len(list2)) if list2[i] in list1])
0

For relatively short lists, you can use a list comprehension:

>>> list1 = [1, 2]
>>> list2 = [1, 2, 2, 3]
>>> [i for i, l in enumerate(list2) if l in list1]
[0, 1, 2]

If your lists contain thousands of elements or more, you should consider using numpy instead.