Skip to content

Instantly share code, notes, and snippets.

@saintsGrad15
Created August 19, 2023 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saintsGrad15/5f68c92eb6cc828d450e1cfe8fcb7a61 to your computer and use it in GitHub Desktop.
Save saintsGrad15/5f68c92eb6cc828d450e1cfe8fcb7a61 to your computer and use it in GitHub Desktop.
Iterate over `iterable` yielding only indices between `start_index` and `end_index` inclusive and exclusive, respectively.
import math
from typing import Iterable
def slice_generator(iterable: Iterable, *, start_index: int = 0, end_index: int = math.inf):
"""
Iterate over `iterable` yielding only indices
between `start_index` and `end_index` inclusive and exclusive, respectively.
:param iterable: Any iterable
:param start_index: The first index to yield (inclusive).
:param end_index: The first index to NOT yield (exclusive).
:yield: Indices of `iterable` between `start_index` and `end_index` inclusive and exclusive, respectively.
"""
for index, item in enumerate(iterable):
if index >= start_index:
if index < end_index:
yield item
else:
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment