itertools.izip brokeness

Bengt Richter bokr at oz.net
Fri Jan 6 04:19:07 EST 2006


On 5 Jan 2006 14:34:39 -0800, rurpy at yahoo.com wrote:

>
>Bengt Richter wrote:
>> On 5 Jan 2006 15:48:26 GMT, Antoon Pardon <apardon at forel.vub.ac.be> wrote:
>>
>> >On 2006-01-04, rurpy at yahoo.com <rurpy at yahoo.com> wrote:
>> >><rurpy at yahoo.com> wrote:
>> >>> But here is my real question...
>> >>> Why isn't something like this in itertools, or why shouldn't
>> >>> it go into itertools?
>> >>
>> >>
>> >>   4) If a need does arise, it can be met by __builtins__.map() or by
>> >>      writing:  chain(iterable, repeat(None)).
>> >>
>> >> Yes, if youre a python guru.  I don't even understand the
>> >> code presented in this thread that uses chain/repeat,
>> >
>> >And it wouldn't work in this case. chain(iterable, repeat(None))
>> >changes your iterable into an iterator that first gives you
>> >all elements in the iterator and when these are exhausted
>> >will continue giving the repeat parameter. e.g.
>> >
>> >  chain([3,5,8],repeat("Bye")
>> >
>> >Will produce  3, 5 and 8 followed by an endless stream
>> >of "Bye".
>> >
>> >But if you do this with all iterables, and you have to
>> >because you don't know which one is the smaller, all
>> >iterators will be infinite and izip will never stop.
>>
>> But you can fix that (only test is what you see ;-) :
>>
>>  >>> from itertools import repeat, chain, izip
>>  >>> it = iter(lambda z=izip(chain([3,5,8],repeat("Bye")), chain([11,22],repeat("Bye"))):z.next(), ("Bye","Bye"))
>>  >>> for t in it: print t
>>  ...
>>  (3, 11)
>>  (5, 22)
>>  (8, 'Bye')
>>
>> (Feel free to generalize ;-)
>
>Which just reinforces my original point: if leaving
>out a feature is justified by the existence of some
>alternate method, then that method must be equally
>obvious as the missing feature, or must be documented
>as an idiom.  Otherwise, the justification fails.
>
>Is the above code as obvious as
>  izip([3,5,8],[11,22],sentinal='Bye')?
>(where the sentinal keyword causes izip to iterate
>to the longest argument.)
>
You are right. I was just responding with a quick fix to the
problem Antoon noted.
For a more flexible izip including the above capability, but
also abble to do the default izip with a capability of continuing iteration
in the above mode after the normal izip mode stops, see izip2.py in my other
post in this thread.

Regards,
Bengt Richter



More information about the Python-list mailing list