![](https://secure.gravatar.com/avatar/3b93c8471f584d466a4005bf32cf02c5.jpg?s=120&d=mm&r=g)
On 1 July 2013 12:57, Oscar Benjamin <oscar.j.benjamin@gmail.com> wrote:
On 30 June 2013 00:51, Nick Coghlan <ncoghlan@gmail.com> wrote:
[x for x in iterable; break if x is None] [x for x in data if x; break if x is None]
One nice advantage of that notation is that:
1. The statement after the ";" is exactly the statement that would appear in the expanded loop 2. It can be combined unambiguously with a filtering clause 3. It clearly disallows its use with nested loops in the comprehension
It has the significant disadvantage that Steven pointed out which is that it doesn't read very well. The most important aspect of a comprehension is its comprehensibility. Consider getting the prime numbers less than 100:
primes100 = {p for p in primes(); break if p >= 100}
You need to invert the if condition to understand which primes are in the resulting set. With for/while it reads properly and the condition at the right expresses a true property of the elements in the resulting set:
primes100 = {p for p in primes() while p < 100}
If you're telling me that "{p for p in primes() while p < 100}" reads better than "{p for p in primes(); break if p >= 100}" I have to disagree strongly. The "break if" form looks beautiful. I know that this involves my not-suggestion, so I might be biased, but that's what I think.
At the moment the obvious way to get the prime numbers less than 100 would be to do something like:
<STUFF> So you have these: {p for p in takewhile(lambda p: p < 100, primes())} set(takewhile(lambda p: p < 100, primes()) {p for p in primes() while p < 100} {p for p in primes(); break if p >= 100} I like them most bottom-to-top, but I don't think new syntax is a cost worth having. If it is, I'm only accepting of the "break if" form, which adds the least grammar. But not that either, because srsly; a semicolon [youtu.be/M94ii6MVilw, contains profanity] in a comprehension?