Accessing next/prev element while for looping
Paul Rubin
http
Mon Dec 19 03:35:17 EST 2005
Paul Rubin <http://phr.cx@NOSPAM.invalid> writes:
> elts = iter(myarray)
> prev,cur,next = elts.next(),elts.next(),elts.next()
> for next2 in elts:
> do_something_with (prev, cur, next)
> prev,cur,next = cur, next, next2
>
> Of course these fail when there's less than 3 elements.
Ehh, too clever for my own good. This fails with exactly 3 elements.
It was a "shortened" version of
elts = iter(myarray)
prev,cur,next = elts.next(),elts.next(),elts.next()
try:
while True:
do_something_with (prev, cur, next)
prev,cur,next = cur, next, elts.next()
except StopIteration: pass
which is messy, and which could get confused by do_something_with...
raising StopIteration for some reason.
More information about the Python-list
mailing list