a few extensions for the itertools

George Sakkis george.sakkis at gmail.com
Sun Nov 19 23:38:58 EST 2006


Steven D'Aprano wrote:

> > A short description to all the functions:
> >
> > icmp(iterable1, iterable2) -> integer
> > 	Return negative if iterable1 < iterable2,
> > 	zero if iterable1 == iterable1,
> > 	positive if iterable1 > iterable1.
>
>
> What does it mean for an iterable to be less than another iterable? That
> it has fewer items? How do these two iterables compare?
>
> iter([1, 2, None, "foo", 3+2j])
>
> def ones():
>     while 1:
>         yield 1
>
> Which is smaller?

Haven't checked the specific implementation, but I would expect it to
behave like sequences of the same type, i.e. first compare the first
elements of the iterables; if they are equal compare the second
elements, and so on, until the first inequality or until the shorter
one ends. In your example, the second iterable is smaller. Needless to
say, you'd better not compare an infinite iterable with itself ;-)

> > drop(n,iterable) -> iterable
> > 	drops the first n elemetns of iterable and
> > 	return a iterator over the rest
>
> Just like itertools.islice(iterable, n, None)
>
> >>> list(itertools.islice(xrange(20), 15, None))
> [15, 16, 17, 18, 19]
>
> (Aside: I think islice would be so much cleaner if it took keyword
> arguments.)

How about slice notation ? I just posted in the Cookbook an OO wrapper
of itertools that, among other functions, uses slice notation for
islice and "+" for chain. Admittedly, my proposal in the py-3k list to
make iter() return itertools-enabled iterators was overwhelmingly shot
down, but I still like it anyway. FWIW, here's the Cookbook link:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498272

George




More information about the Python-list mailing list