Take lists haystack
and needles
haystack = ['a', 'b', 'c', 'V', 'd', 'e', 'X', 'f', 'V', 'g', 'h']
needles = ['V', 'W', 'X', 'Y', 'Z']
I need to generate a list of the indices at which any element of needles
occurs in haystack
. In this case those indices are 3, 6, and 8 thus
result = [3, 6, 8]
This question I found is very similar and was rather elegantly solved with
result = [haystack.index(i) for i in needles]
Unfortunately, this solution gives ValueError: 'W' is not in list
in my case. This is because the difference here is that an element of needles
may occur in haystack
a number of times or not at all.
In other words, haystack
may contain no needles or it may contain many.
One of the most basic ways to get the index positions of all occurrences of an element in a Python list is by using a for loop and the Python enumerate function. The enumerate function is used to iterate over an object and returns both the index and element.
There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list. And second, use any() function to check if the list contains any elements of another one.
Use List Comprehension and the enumerate() Function to Get the Indices of All Occurrences of an Item in A List. Another way to find the indices of all the occurrences of a particular item is to use list comprehension. List comprehension is a way to create a new list based on an existing list.
The Python index() method helps you find the index position of an element or an item in a string of characters or a list of items. It spits out the lowest possible index of the specified element in the list. In case the specified item does not exist in the list, a ValueError is returned.
haystack = ['a', 'b', 'c', 'V', 'd', 'e', 'X', 'f', 'V', 'g', 'h']
needles = ['V', 'W', 'X', 'Y', 'Z']
st = set(needles)
print([i for i, e in enumerate(haystack) if e in st])
[3, 6, 8]
Even if you used [haystack.index(i) for i in needles if i in haystack]
it would not work as you have repeated elements.
Making st = set(needles)
means we have a linear solution as set lookups are 0(1)
which for large input would be significantly more efficient.
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