PEP 289: Generator Expressions (please comment)

Bjorn Pettersen bjorn.pettersen at comcast.net
Thu Oct 23 21:16:29 EDT 2003


"rzed" <rzantow at ntelos.net> wrote in news:1066956387.364126 at cache1:

> 
> "Raymond Hettinger" <python at rcn.com> wrote in message
> news:5d83790c.0310231158.65595858 at posting.google.com...
>> Peter Norvig's creative thinking triggered renewed interest in PEP
>> 289. That led to a number of contributors helping to re-work the pep
>> details into a form that has been well received on the python-dev
>> list: 
>>
>>     http://www.python.org/peps/pep-0289.html
>>
>> In brief, the PEP proposes a list comprehension style syntax for
>> creating fast, memory efficient generator expressions on the fly:
>>
>>     sum(x*x for x in roots)
>>     min(d.temperature()*9/5 + 32 for d in days)
>>     Set(word.lower() for word in text.split() if len(word) < 5)
>>     dict( (k, somefunc(k)) for k in keylist )
>>     dotproduct = sum(x*y for x,y in itertools.izip(xvec, yvec))
>>     bestplayer, bestscore = max( (p.score, p.name) for p in players )
>>
>> Each of the above runs without creating a full list in memory,
>> which saves allocation time, conserves resources, and exploits
>> cache locality.
>>
>> The new form is highly expressive and greatly enhances the utility
>> of the many python functions and methods that accept iterable
>> arguments. 
>>
> 
> I like it! How about in conjunction with the print statement?
> print "%s\n" % (s for s in strlist)

Wouldn't work in general, i.e. in your version there isn't a way to
supply multiple elements. For a (completely?) general solution see the
Lisp FORMAT function, the ~{ @{ etc. format specifiers
(http://www.lisp.org/HyperSpec/Body/sec_22-3-7-4.html). Perhaps not the
most Pythonic? <grin> 

-- bjorn




More information about the Python-list mailing list