Skip to content

Instantly share code, notes, and snippets.

@raeq
Created August 9, 2020 20:46
Show Gist options
  • Save raeq/e6c655d38fea71ea4a19da350b7a6c5e to your computer and use it in GitHub Desktop.
Save raeq/e6c655d38fea71ea4a19da350b7a6c5e to your computer and use it in GitHub Desktop.
Finds the indices of matching elements in a list.
import typing
def get_indices(the_list: list, test_value: object) -> typing.Iterable[int]:
"""
Returns the indices of matching list items.
Uses a generator to create an iterator.
Args:
the_list: the list containing search elements
test_value: what we want to find
Returns: the index of matching list items
>>> print(list(get_indices(list("The jolly green giant"), "e")))
[2, 12, 13]
"""
generator = (key for key, val in enumerate(the_list) if test_value == val)
for key in generator:
yield key
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment