Skip to content

Instantly share code, notes, and snippets.

@RHDZMOTA
Last active August 21, 2021 18:09
Show Gist options
  • Save RHDZMOTA/7ed262316455238f90c5b4934eb4a6c9 to your computer and use it in GitHub Desktop.
Save RHDZMOTA/7ed262316455238f90c5b4934eb4a6c9 to your computer and use it in GitHub Desktop.
Get the last element of any python iterator.
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