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?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With