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

Daniel Schüle uval at rz.uni-karlsruhe.de
Tue Dec 6 08:47:12 EST 2005


Hello NG,

I am wondering if there were proposals or previous disscussions in this 
NG considering using 'while' in comprehension lists

# 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)



usually I would prefer one liners like
lines=[line.strip() for line in file("foo").readlines() if line]
they make the purpose clear
so if 'while' were allowed in comprehension list this would allow
to write concise code

to the example above, I tried a workaround
i=2
lst=[i**=2 for _ in iter(lambda:_<1000, False)]

but this failes with SyntaxError because of i**=2
and must be also rewritten into

 >>> i=2
 >>> def f():
...     global i
...     i**=2
...     return i
...
 >>> lst=[f() for _ in iter(lambda:i<1000, False)]
 >>> lst
[4, 16, 256, 65536]

I think this loses compared with
i=2
lst=[i**=2 while i<1000]

Regards, Daniel




More information about the Python-list mailing list