Created
October 15, 2020 14:27
-
-
Save MatthewWilkes/2c5b10eb5e9bf45f0bd077bbdf9f54d6 to your computer and use it in GitHub Desktop.
How to get 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 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