Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the indices at which any element of one list occurs in another

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.

like image 607
chambln Avatar asked Apr 05 '15 00:04

chambln


People also ask

How do you find the index of all occurrences in a list?

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.

How do you check if elements of one list are in another?

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.

How do you get the all the indexes of particular element in a list Python?

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.

What is the index () method used for in terms of lists?

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.


1 Answers

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.

like image 172
Padraic Cunningham Avatar answered Oct 17 '22 08:10

Padraic Cunningham