Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find indices of first two elements in a list that are any of the elements in another list?

Tags:

python

How do I find the indices of the first two elements in a list that are any of the elements in another list?

For example:

story = ['a', 'b', 'c', 'd', 'b', 'c', 'c']
elementsToCheck = ['a', 'c', 'f', 'h']

In this case, the desired output is a list indices = [0,2] for strings 'a' and 'c'.

like image 713
jo_ Avatar asked Oct 10 '20 11:10

jo_


People also ask

How do you get the indices of all occurrences of an element in a list in Python?

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 index the first element in a list?

To access the first element (12) of a list, we can use the subscript syntax [ ] by passing an index 0 . In Python lists are zero-indexed, so the first element is available at index 0 . Similarly, we can also use the slicing syntax [:1] to get the first element of a list in Python.


2 Answers

story = ['a', 'b', 'c', 'd', 'b', 'c', 'c']
elementsToCheck = ['a', 'c', 'f', 'h']

out = []
for i, v in enumerate(story):
    if v in elementsToCheck:
        out.append(i)
    if len(out) == 2:
        break

print(out)

Prints:

[0, 2]
like image 114
Andrej Kesely Avatar answered Sep 28 '22 18:09

Andrej Kesely


Possibly the shortest way to implement this:

[i for i, x in enumerate(story) if x in elementsToCheck][:2]
like image 32
Gil Pinsky Avatar answered Sep 28 '22 17:09

Gil Pinsky