Skip to content

Instantly share code, notes, and snippets.

@singularitti
Created April 7, 2019 22:45
Show Gist options
  • Save singularitti/0446531b3c547b592a4080ae53f49885 to your computer and use it in GitHub Desktop.
Save singularitti/0446531b3c547b592a4080ae53f49885 to your computer and use it in GitHub Desktop.
Generates pairs where the first element is an item from the iterable source and the second element is a boolean flag indicating if it is the last item in the sequence. #Python #iterate
def iter_islast(iterable):
"""
iter_islast(iterable) -> generates (item, islast) pairs
Generates pairs where the first element is an item from the iterable
source and the second element is a boolean flag indicating if it is
the last item in the sequence.
Referenced from
`here <http://code.activestate.com/recipes/392015-finding-the-last-item-in-a-loop/>`_.
.. doctest::
>>> for n, islast in iter_islast(range(4)):
... if islast:
... print "last but not least:",
... print n
...
0
1
2
last but not least: 3
>>> list(iter_islast(''))
[]
>>> list(iter_islast('1'))
[('1', True)]
>>> list(iter_islast('12'))
[('1', False), ('2', True)]
>>> list(iter_islast('123'))
[('1', False), ('2', False), ('3', True)]
"""
it = iter(iterable)
prev = it.next()
for item in it:
yield prev, False
prev = item
yield prev, True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment