Take the lists haystackandneedles
haystack = ['a', 'b', 'c', 'V', 'd', 'e', 'X', 'f', 'V', 'g', 'h']
needles = ['V', 'W', 'X', 'Y', 'Z']
I need to create a list of indexes at which any item needlesoccurs in haystack. In this case, these indices are 3, 6 and 8, therefore
result = [3, 6, 8]
This question I found is very similar and was pretty elegantly resolved with
result = [haystack.index(i) for i in needles]
Unfortunately, this solution gives ValueError: 'W' is not in listin my case. This is due to the fact that the difference here is that the element needlescan occur haystackseveral times or even absent.
In other words, it haystackmay not contain needles or may contain a lot.