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'.
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.
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.
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]
Possibly the shortest way to implement this:
[i for i, x in enumerate(story) if x in elementsToCheck][:2]
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