Skip to content

Instantly share code, notes, and snippets.

@raeq
Created August 12, 2020 19:41
Show Gist options
  • Save raeq/71b29e98061d41e0b9f54c696ff8c68f to your computer and use it in GitHub Desktop.
Save raeq/71b29e98061d41e0b9f54c696ff8c68f to your computer and use it in GitHub Desktop.
Iterators and large lists.
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("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