Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python find indices of elements in one list that are not in the other list

Tags:

python

list

list_1 = ["a", "b", "c", "d", "e"]
list_2 = ["a", "c", "d"] 

I want the indices of elements in list_1 that are not in list_2. Here I would expect

[1, 4]

For my case, list_2 is a subset of list_1 and all elements are unique. Is there a better way to do this without using explicit loops?

like image 366
midi Avatar asked Dec 14 '22 10:12

midi


1 Answers

You can use a conditional list comprehension:

>>> [i for i, item in enumerate(list_1) if item not in list_2]
[1, 4]

This solution has a time complexity of O(n*m). For bigger lists, it makes sense to convert list_2 to a set as it is much faster to search in a set. The following solution is O(n):

>>> set_2 = set(list_2)
>>> [i for i, item in enumerate(list_1) if item not in set_2]
[1, 4]
like image 80
Selcuk Avatar answered Feb 08 '23 23:02

Selcuk