getting n items at a time from a generator

Shane Geiger sgeiger at ncee.net
Thu Jan 10 22:36:31 EST 2008


Paul Rubin wrote:
> Tim Roberts <timr at probo.com> writes:
>   
>> I have to say that I have found this to be a surprisingly common need as
>> well.  Would this be an appropriate construct to add to itertools?
>>     
>
> I'm in favor.
>   


I am ecstatic about the idea of getting n items at a time from a
generator!  This would eliminate the use of less elegant functions to do
this sort of thing which I would do even more frequently if it were
easier. 

Is it possible that this syntax for generator expressions could be adopted?

>>> sentence = 'this is a senTence WiTH'
>>> generator = (word.capitalize() for word in sentence.split())
>>> print generator.next(3,'PadValue')
('This','Is','A')
>>> print generator.next(3,'PadValue')
('Sentence','With','PadValue')
>>> generator.next(3,'PadValue')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>


While on the topic of generators:

Something else I have longed for is assignment within a while loop.  (I
realize this might be more controversial and might have been avoided on
purpose, but I wasn't around for that discussion.)


>>> sentence = 'this is a senTence WiTH'
>>> generator = (word.capitalize() for word in sentence.split())
>>> while a,b,c = generator.next(3,'PadValue'):
...     print a,b,c
...
This Is A
Sentence With PadValue
>>>




-- 
Shane Geiger
IT Director
National Council on Economic Education
sgeiger at ncee.net  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy




More information about the Python-list mailing list