i=2; lst=[i**=2 while i<1000]

Steve Holden steve at holdenweb.com
Tue Dec 6 10:44:33 EST 2005


Daniel Schüle wrote:
> hi,
> 
> [...]
> 
> 
>>># pseudo code
>>>i=2
>>>lst=[i**=2 while i<1000]
>>>
>>>of course this could be easily rewritten into
>>>i=2
>>>lst=[]
>>>while i<1000:
>>>    i**=2
>>>    lst.append(i)
>>>
>>
>>
>>Neither of these loops would terminate until memory is exhausted. Do you 
>>have a use case for a 'while' in a list comprehension which would 
>>terminate?
> 
> 
> unless I am missing something obvious, I can not see why the loop should 
> not terminate

In that case, kindly explain how the condition i<1000 can become false 
when it starts at 2 and never changes! [In other words: you *are* 
missing something obvious].

> sure pseudo code is not executable but the other one works
> while tests the boolean expression first then decides whether to execute
> the body or not, in particular no next-iterator is involved(??)
> as it would be in
> lst=range(5)
> for i in lst:
> 	del lst[0]
> 
Indeed. But the test condition is initially true, and can never become 
false, so the loop is endless. It will probably eventually terminate by 
throwing a MemoryError exception when lst and its element values use up 
all available space.

Don't you have an interpreter you could run the code in to verify that 
it does indeed loop interminably? You seem to be assuming that the 
expression i**2 changes the value of i. It doesn't.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list