a few extensions for the itertools

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Mon Nov 20 06:41:52 EST 2006


On Mon, 20 Nov 2006 09:54:41 +0100, Mathias Panzenboeck wrote:

> Steven D'Aprano wrote:
>> On Sun, 19 Nov 2006 21:35:24 +0100, Mathias Panzenboeck wrote:
>> 
>>> I wrote a few functions which IMHO are missing in python(s itertools).
>>>
>>> You can download them here:
>>> http://sourceforge.net/project/showfiles.php?group_id=165721&package_id=212104
>>>
>>> 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?
>> 
>> 
> 
> it's like cmp on lists, but on iterables.
> 
> [1,2,3] < [1,2,4]
> [1,2,3] < [1,2,3,0]


But that meaningless, as far as I can see. Lists and iterators aren't the
same thing. A list is a collection; an iterator is not, but it can be
accumulated into a collection.

If equality is meaningful for an object, you should be able to test for
equality without changing the object. But that isn't true for iterators.

Worse, because comparing an iterator consumes items, you can easily get
crazy results like the following:


>>> L = [1, 2, 3, 4, 5]
>>> def it():
...     yield 5; yield 0; yield 0; yield 0; yield 0
... 
>>> it = it()

Now, we can compare the first item of L with the first item of it:

>>> L[0] < it.next()  # if True, L < it
True

So L must be less than it, right? Let's print both objects out in full to
check:

>>> print L
[1, 2, 3, 4, 5]
>>> print list(it) # if L < it, it must be > L
[0, 0, 0, 0]

Oops.

I think the GENERAL concept of comparison between iterators is
meaningless. A lazy comparison between the items of an iterator and some
other iterable may be a useful thing to do, but as a general concept,
saying that an iterator compares bigger or smaller or equal to something
else doesn't make sense, since the mere fact that you make that comparison
will change the iterator.


-- 
Steven.




More information about the Python-list mailing list