Proposal: [... for ... while cond(x)]

Rick Zantow rzantow at gmail.com
Mon Aug 7 07:18:11 EDT 2006


Duncan Booth <duncan.booth at invalid.invalid> wrote in 
news:Xns981854A828521duncanbooth at 127.0.0.1:

> Diez B. Roggisch wrote:
> 
>>> No, the list comprehension lets you write an expression directly
>>> avoiding a function call, and it also allows you to add in a
>>> condition which can be used to filer the sequence. Your proposal 
adds
>>> nothing. 
>> 
>> It does. Consider this:
>> 
>> whatever = [x for x in xrange(1000000000) while  x < 10]
>> 
>> 
>> That would run only in a splitsecond of what the whole listcomp 
would.
> 
> Except that the comparable listcomp today is:
> 
> whatever = [x for x in takewhile(lambda x: x < 10, xrange
(1000000000))]
> 
> which also runs in a split second.
> 
> Actually, the OP was correct, it does add something: it removes the 
need 
> for a function or lambda in the takewhile just as the original 
listcomp 
> removes a function or lambda compared with the map version.
> 

Consider how it would be if the situation were reversed, and
whatever = [x for x in xrange(1000000000) while  x < 10] was the 
convention today. What advantage would there be to replacing it with 
whatever = [x for x in takewhile(lambda x: x < 10, xrange(1000000000))]?

As a newcomer to Python, I'd find the first syntax far more readily 
graspable, and I'd have to wonder why I'd ever need takewhile and lambda 
just to do what appears to be straightforward conditioning of a loop. 

I'm not a newcomer to Python, and I wonder about that anyway. 

I also note this, using Python 2.4.2 on win32:
>>> whatever = [x for x in takewhile(lambda x: x < 10, xrange
(1000000000))]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'takewhile' is not defined

So in addition to the two functions, I need an import statement. It 
looks like the argument can certainly be made that simplifying the 
syntax and lightening the call load bring some advantage to the table. 
There are other arguments to be made against the proposed syntax, I'm 
sure.

-- 
rzed




More information about the Python-list mailing list