[Python-ideas] while conditional in list comprehension ?? (original) (raw)
Steven D'Aprano steve at pearwood.info
Tue Jan 29 02:30:56 CET 2013
- Previous message: [Python-ideas] while conditional in list comprehension ??
- Next message: [Python-ideas] while conditional in list comprehension ??
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 29/01/13 10:27, Terry Reedy wrote:
[n for n in range(1,1000) while n < 400] This would translate as def temp(): res = [] for n in range(1, 1000): while n < 400): res.append(n) return res temp() which makes an infinite loop, not a truncated loop.
Why would it translate that way? That would be a silly decision to make. Python can decide on the semantics of a while clause in a comprehension in whatever way makes the most sense, not necessarily according to some mechanical, nonsensical translation.
We could easily decide that although [n for n in range(1,1000) if n < 400] has the semantics of:
res = [] for n in range(1, 1000): if n < 400): res.append(n)
[n for n in range(1,1000) while n < 400] could instead have the semantics of:
res = [] for n in range(1, 1000): if not (n < 400): break res.append(n)
If it were decided that reusing the while keyword in this way was too confusing (which doesn't seem likely, since it is a request that keeps coming up over and over again), we could use a different keyword:
[n for n in range(1,1000) until n >= 400]
What you actually want is
res = [] for n in range(1, 1000): if >= 400): break res.append(n) which is not the form of a comprehension.
Why not? Was the idea of a comprehension handed down from above by a deity, never to be changed? Or is it a tool to be changed if the change makes it more useful?
Mathematical set builder notation has no notion of "break" because it is an abstraction. It takes exactly as much effort (time, memory, resources, whatever) to generate these two mathematical sets:
{1} {x for all x in Reals if x == 1}
(using a hybrid maths/python notation which I hope is clear enough).
To put it another way, mathematically the list comp [p+1 for p in primes()] is expected to run infinitely fast. But clearly Python code is not a mathematical abstraction. So the fact that mathematical set builder notation does not include any way to break out of the loop is neither here nor there. Comprehensions are code, and need to be judged as code, not abstract mathematical identities.
-- Steven
- Previous message: [Python-ideas] while conditional in list comprehension ??
- Next message: [Python-ideas] while conditional in list comprehension ??
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]