islast: handling the last element of an iterator

Doing something special for the last element of an iterator is a fairly common pattern. I needed it for the Python Jtag tools, so made this small wrapper:

def islast(o):
    it = o.__iter__()
    e =
    while True:
            nxt =
            yield (False, e)
            e = nxt
        except StopIteration:
            yield (True, e)

In use, it is a little like the builtin enumerate:

>>> for i in islast(range(4)): print i
(False, 0)
(False, 1)
(False, 2)
(True, 3)


for (last,e) in islast(collection):
  if not last:
    # do something with e
    # do something with the last e

The trick is that the iterator in islast() is one element ahead, so can know when the current element is the last one. Simple.