itertools.izip brokeness

Bengt Richter bokr at oz.net
Thu Jan 5 17:14:45 EST 2006


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 ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list