Python-list Digest, Vol 80, Issue 223

Chris Rebert clp2 at rebertia.com
Tue May 25 16:14:36 EDT 2010


On Tue, May 25, 2010 at 1:01 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Tue, May 25, 2010 at 1:10 PM,  <python-list-request at python.org> wrote:
>> ---------- Forwarded message ----------
>> From: Terry Reedy <tjreedy at udel.edu>
>> To: python-list at python.org
>> Date: Tue, 25 May 2010 13:09:23 -0400
>> Subject: Re: Generator expressions vs. comprehensions
>> On 5/25/2010 3:08 AM, Peter Otten wrote:
>>>
>>> Michele Simionato wrote:
>>
>>> I think not turning the list-comp into syntactic sugar for list(genexp) in
>>> py3 is a missed opportunity.
>>
>> Implementing it that way was tried but was much slower than the current implementation. If one uses StopIteration as it is intended to be used (and is so documented), then, I believe, they are equivalent. There was a conscious decision to not slow comprehensions for the many to cater to the very few.
>
> I thought that I was using it as intended.  The full function that I
> was working with when I ran into the problem was:
>
> def tuples(iterable, n=2):
>    """Make an iterator that returns elements from iterable in tuples of n.  If
>    the number of elements from the iterable is not a multiple of n, any
>    trailing elements will be truncated.
>
>    tuples('ABCDEFG', n=2) --> ('A', 'B') ('C', 'D') ('E', 'F')
>    """
>    iterator = iter(iterable)
>    while True:
>        yield tuple(iterator.next() for i in xrange(n))
>
> The intention being that if iterator.next() raised a StopIteration, it
> would propagate out and signal no further values for the tuples
> generator.  Instead, the generator expression results in empty tuples
> once the iterator has run out, and the tuples generator never runs
> out.  This has since been fixed by replacing the generator expression
> with a for loop, but if you don't mind my asking, how does this
> violate the documented usage pattern?  Is the recommendation to use an
> explicit try-except around every call of iterator.next()?
>
> Off-topic, does anybody know of a better name for this function?

truncating_grouper() ?

from itertools import izip
def truncating_grouper(n, iterable):
    "truncating_grouper(3, 'ABCDEFG') --> ABC DEF"
    args = [iter(iterable)] * n
    return izip(*args)

Implementation adapted from itertools's docs's "Recipes" section.

Also, avoid replying to digests in the future; it messes up
conversation threading.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list