Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created October 19, 2018 12:10
Show Gist options
  • Save vlad-bezden/4c5f815d2c924864da583e7fc997b1ce to your computer and use it in GitHub Desktop.
Save vlad-bezden/4c5f815d2c924864da583e7fc997b1ce to your computer and use it in GitHub Desktop.
Yield each iterable item along with the item before it
def couple(iterable, *, first=None):
"""Yield each iterable item along with the item before it."""
prev = first
for item in iterable:
yield prev, item
prev = item
# >>> list(couple(range(5)))
# >>> [(None, 0), (0, 1), (1, 2), (2, 3), (3, 4)]
# >>> list(couple(range(5), first=10))
# >>> [(10, 0), (0, 1), (1, 2), (2, 3), (3, 4)]
@vlad-bezden
Copy link
Author

it also shows how to use * for requiring keyword-only arguments without capturing unlimited positional arguments. So, no call like this allowed.

couple(range(5), 10)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-70-13870c826a4b> in <module>
----> 1 list(couple(range(5), 10))

TypeError: couple() takes 1 positional argument but 2 were given

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment