Skip to content

Instantly share code, notes, and snippets.

@nathan-cruz77
Created August 22, 2019 03:13
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 nathan-cruz77/6eb8ef84830253abc71827a5a374ad05 to your computer and use it in GitHub Desktop.
Save nathan-cruz77/6eb8ef84830253abc71827a5a374ad05 to your computer and use it in GitHub Desktop.
Fold iterable
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