Last active
January 20, 2025 15:59
-
-
Save moreati/744de5f0784da4ebc8be06d48d2612ae to your computer and use it in GitHub Desktop.
Python generator that flags the last item in an iterable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import collections | |
from typing import Generator, Iterable, TypeVar | |
T = TypeVar('T') | |
def flag_last(iterable:Iterable[T]) -> Generator[None, tuple[T, bool], None]: | |
""" | |
Yield (item, is_last) for each item in iterable, is_last is True on the | |
last item, False otherwise. | |
>>> list(flag_last(range(0))) | |
[] | |
>>> list(flag_last(range(1))) | |
[(0, True)] | |
>>> list(flag_last(range(3))) | |
[(0, False), (1, False), (2, True)] | |
""" | |
iterator = iter(iterable) | |
queue = collections.deque(maxlen=2) | |
try: | |
queue.append(next(iterator)) | |
except StopIteration: | |
return | |
for item in iterator: | |
queue.append(item) | |
yield queue.popleft(), False | |
yield queue.popleft(), True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment