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 = it.next()
    while True:
        try:
            nxt = it.next()
            yield (False, e)
            e = nxt
        except StopIteration:
            yield (True, e)
            break

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)

or:

for (last,e) in islast(collection):
  if not last:
    # do something with e
  else:
    # 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.