Created
August 22, 2019 03:13
-
-
Save nathan-cruz77/6eb8ef84830253abc71827a5a374ad05 to your computer and use it in GitHub Desktop.
Fold iterable
This file contains 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 itertools import chain | |
# Fold iterable into itself. | |
# | |
# | |
# Sample usage: | |
# | |
# >>> list(fold([1, 2, 3])) | |
# [1, 2, 3, 2, 1] | |
# | |
# >>> list(fold([1, 2])) | |
# [1, 2, 1] | |
# | |
def fold(iterator): | |
reverse = reversed(iterator) | |
next(reverse, None) | |
return chain(iterator, reverse) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment