Source

pythonwise / istail.py

from itertools import chain

def istail(it):
    '''Check if iterator has exactly one more element.
    Return True/False and iterator.'''
    try:
        i = next(it)
    except StopIteration:
        return False, it

    try:
        j = next(it)
        return False, chain([i, j], it)
    except StopIteration:
        return True, chain([i], it)

def ipeek(it):
    '''Peek into iterator, return first element and iterator.'''
    item = next(it)
    return item, chain([item], it)

def _test():
    t, it = istail(iter([]))
    print(t, list(it))
    t, it = istail(iter([1]))
    print(t, list(it))
    t, it = istail(iter([1, 2]))
    print(t, list(it))

    items = (i for i in range(5))
    i, items = ipeek(items)
    print(i, list(items))

if __name__ == '__main__':
    _test()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.