Accessing next/prev element while for looping

Bas wegwerp at gmail.com
Sun Dec 18 07:58:39 EST 2005


Just make a custom generator function:

>>> def prevcurnext(seq):
	it = iter(seq)
	prev = it.next()
	cur = it.next()
	for next in it:
		yield (prev,cur,next)
		prev,cur = cur, next


>>> for (a,b,c) in prevcurnext(range(10)):
	print a,b,c

	
0 1 2
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9

Cheers,
Bas




More information about the Python-list mailing list