Last active
August 21, 2021 18:09
-
-
Save RHDZMOTA/7ed262316455238f90c5b4934eb4a6c9 to your computer and use it in GitHub Desktop.
Get the last element of any python iterator.
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
from typing import Any, Iterator, Optional | |
def last(iterator: Iterator[Any]) -> Optional[Any]: | |
last = None | |
for last in iterator: | |
continue | |
return last | |
assert(last(iterator=(i for i in range(10))) == 9) # Generator | |
assert(last(iterator={"Alice": 1, "Bob": 2, "Carol": 3}) == "Carol") # Dictionary | |
assert(last(iterator=[1, 2, 3]) == 3) # List | |
assert(last(iterator="abcde") == "e") # String | |
assert(last(iterator=[]) is None) # Empty List | |
assert(last(iterator="") is None) # Empty String | |
print("All tests passed.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment