itertools comments [Was: Re: RELEASED: Python 2.3a2]

Jimmy Retzlaff jimmy at
Fri Feb 21 00:46:41 CET 2003

Raymond Hettinger (vze4rx4y at wrote:
> "Alexander Schmolck"
>> def xwindow(iter, n=2, s=1):
>>     r"""Move an `n`-item (default 2) windows `s` steps (default 1) at

>>a time
>>     over `iter`.
>I've needed this one only one time in twenty-five years of programming 
>(for the markov algorithm).  Again, solid use cases are needed.

I've used something like this several times in recent weeks when doing
some simple computational geometry. One way to store a polygon is as a
sequence of points that represent the vertices of the polygon. If you
want to perform some operation on the edges of the polygon, an xwindow
style iterator can be used to iterate over consecutive pairs of points.
One nuance in this domain is that sometimes polygons are represented as:

[p0, p1, p2]

where each p is a distinct point. But at other times the starting point
is repeated at the end for various reasons:

[p0, p1, p2, p0]

xwindow as shown above would do just fine when the starting point is
repeated (i.e., it would yield all the edges). But in the first
representation above, either an option would be needed to tell the
iterator to "wrap" around until the beginning of the "window" has gone
through all the elements of xwindow's parameter, or it would have to be
used in a manner similar to:

for edge in xwindow(polygon + [polygon[0]]):
    if thisisthebleeding(edge):
        print 'this is new stuff'

This can be ugly if the polygon is large (one of the motivations for
using iterators in the first place). Of course, something like itercat
from could
be used here. Come to think of it, I'd probably use itercat even more
often than xwindow. I can see how following use cases like this could
lead to the size of itertools exploding pretty quickly.


More information about the Python-list mailing list