getting n items at a time from a generator

Terry Jones terry at jon.es
Sat Dec 29 15:01:22 EST 2007


Hi Igor

>>>>> "Igor" == Igor V Rafienko <igorr at ifi.uio.no> writes:

>> Also consider this solution from O'Reilly's Python Cookbook (2nd Ed.)
>> p705
>> 
>> def chop(iterable, length=2):
>> return izip(*(iter(iterable),) * length)

Igor> Is this *always* guaranteed by the language to work? Should the
Igor> iterator returned by izip() change the implementation and evaluate
Igor> the underlying iterators in, say, reverse order, the solution would
Igor> no longer function, would it? Or is it something the return value of
Igor> izip() would never do?

Igor> (I am just trying to understand the solution, not criticize it. Took
Igor> a while to parse the argument(s) to izip in the example).

I had to look at it a bit too.  I actually deleted the comment I wrote
about it in my own code before posting it here and decided to simply say
"consider" in the above instead :-)

As far as I understand it, you're right. The docstring for izip doesn't
guarantee that it will pull items from the passed iterables in any order.
So an alternate implementation of izip might produce other results. If it
did them in reverse order you'd get each n-chunk reversed, etc.

Terry



More information about the Python-list mailing list