'while' in list comprehension?

Stephen Horne steve at ninereeds.fsnet.co.uk
Thu Oct 23 18:57:31 EDT 2003


On Wed, 22 Oct 2003 22:57:42 -0400, "Terry Reedy" <tjreedy at udel.edu>
wrote:

>while is simply not same as if: break!
>if executes once for each value of i, while indefinitely.
>If you translate back by current rule, which will not change, you get:
>

'while' is an English word which has meaning independant of the
existing Python 'while' loop. It is not necessarily wrong to apply a
different aspect of that meaning in a list comprehension.

Besides, I read the syntax as equating to...

foo = []
for i in bar while len(i) >0:
     foo.append(i)

Yes, I know that isn't a legal Python loop. My point is that it didn't
look like a nested loop to me, but rather like an additional qualifier
on the existing loop.

That said, you do have a point - multiple 'for' parts in a list
comprehension act as nested loops, so maybe a while part should too.

The trouble is that a standalone while loop probably makes little
sense in a list comprehension - sure you have a place to put the loop
condition, but what about the initialisation and body?

If there were a real while-part in a list comprehension, it would
probably need those things to become explicit (becoming a lot like the
C for loop) - something like...

  [k while k=1; k<1024; k*=2]

Hmmmm...

  while i=0; i<10; i++ :
    print i

Hmmmm....

Nah - damn silly idea.


-- 
Steve Horne

steve at ninereeds dot fsnet dot co dot uk




More information about the Python-list mailing list