Accessing next/prev element while for looping

Peter Otten __peter__ at web.de
Mon Dec 19 07:15:02 EST 2005


Bengt Richter wrote:

> >>> def pcniter(seq, NULL=NotImplemented):
> ...     seqiter = iter(seq)
> ...     prev = curr = NULL
> ...     try: next = seqiter.next()
> ...     except StopIteration: return
> ...     for item in seqiter:
> ...         prev, curr, next = curr, next, item
> ...         yield prev, curr, next
> ...     yield curr, next, NULL
> ...


Just a reminder: 

"""
In a generator function, the return statement is not allowed to include
an expression_list[3]. In that context, a bare return indicates that the
generator is done and will cause StopIteration to be raised.
"""

try:
    # may raise StopIteration
except StopIteration:
   return

is the same as

try:
    # may raise StopIteration
except StopIteration:
    raise StopIteration

and may be simplified to

# may raise StopIteration

Peter



More information about the Python-list mailing list