Best way to check that you are at the beginning (the end) of an iterable?

Chris Rebert clp2 at rebertia.com
Wed Sep 7 22:27:09 EDT 2011


On Wed, Sep 7, 2011 at 5:24 PM, Miki Tebeka <miki.tebeka at gmail.com> wrote:
> I guess enumerate is the best way to check for first argument. Note that if someone passes you the iterator as argument you have now way of checking if the consumed items from it.
>
> istail can be implemented using itertools.chain, see https://gist.github.com/1202260

For the archives, if Gist ever goes down:

from itertools import chain

def istail(it):
    '''Check if iterator has 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)


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)



More information about the Python-list mailing list