[Python-ideas] "While" suggestion

Steven Bethard steven.bethard at gmail.com
Wed Jul 30 07:29:23 CEST 2008


On Tue, Jul 29, 2008 at 8:55 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> Steven Bethard wrote:
>> On Tue, Jul 29, 2008 at 3:19 PM, Terry Reedy <tjreedy at udel.edu> wrote:
>>> Roman Susi wrote:
>>>> Python already has dict/list literals + list comprehensions.
>>>
>>> Better to think that Python has generator expressions which can be used
>>> in list, set, and dict comprehensions (the latter two in 3.0 and maybe 2.6).
>>
>> You probably don't want to think about it that way - a list/set/dict
>> comprehension does not actually create a generator.
>
> Yes I do.  For normal purposes, in 3.0, [genexp] == list(genexp), and so on.
>  That it do something else internally for efficiency is implementation
> detail, not semantics.

But the semantics are pretty different. The semantics are basically:

    def _(seq):
        _1 = []
        for x in seq:
            _1.append(<expression with x>)
        return _1
    return _(seq)

    def _(seq):
        for x in seq:
            yield <expression with x>
    return list(_(seq))

Yes, they produce the same results, but semantically they're
different. In one case, a list is created and items are appended to it
and then that list is returned. In the other case, a generator object
is created, and then that generator is repeatedly resumed to yield
items by the list() constructor.

I think it's fine to say they achieve the same result, but I think
saying they're really the same thing is a mistake.

Steve

P.S. Yes, it's executed in a different scope - that's why the code I
showed you before had to do ``dict_comp.__code__.co_consts[1]``
instead of just ``dict_comp.__code__``.


-- 
I'm not *in*-sane. Indeed, I am so far *out* of sane that you appear a
tiny blip on the distant coast of sanity.
 --- Bucky Katt, Get Fuzzy



More information about the Python-ideas mailing list