Skip to content

Instantly share code, notes, and snippets.

@MatthewWilkes
Created October 15, 2020 14:27
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 MatthewWilkes/2c5b10eb5e9bf45f0bd077bbdf9f54d6 to your computer and use it in GitHub Desktop.
Save MatthewWilkes/2c5b10eb5e9bf45f0bd077bbdf9f54d6 to your computer and use it in GitHub Desktop.
How to get the last item in an iterable
import typing as t
T_iter = t.TypeVar("T_iter")
def which_is_last(data: t.Iterable[T_iter]) -> t.Iterator[t.Tuple[T_iter, bool]]:
"""Given an iterable, return an iterable of value, bool pairs
where the bool is True iff this is the last item."""
last_found: T_iter
has_value = False
for item in data:
if has_value:
yield last_found, False
last_found = item
has_value = True
else:
if has_value:
yield last_found, True
if __name__ == "__main__":
for item, last in which_is_last([1, 2, 3]):
print(item, last)
for item, last in which_is_last(a for a in range(5)):
print(item, last)
for item, last in which_is_last([]):
print(item, last)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment