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

Bengt Richter bokr at oz.net
Tue Dec 6 12:08:43 EST 2005


On Tue, 06 Dec 2005 15:44:33 +0000, Steve Holden <steve at holdenweb.com> wrote:

>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.
>
No, but i**=2 does. Are you two talking about the same code?

 >>> i=2
 >>> lst=[]
 >>> while i<1000:
 ...     i**=2
 ...     lst.append(i)
 ...
 >>> lst
 [4, 16, 256, 65536]

Regards,
Bengt Richter



More information about the Python-list mailing list