Steve D'Aprano <steve+pyt...@pearwood.info> writes:
> Every few years, the following syntax comes up for discussion, with
> some people saying it isn't obvious what it would do, and others
> disagreeing and saying that it is obvious. So I thought I'd do an
> informal survey.
> What would you expect this syntax to return?
> [x + 1 for x in (0, 1, 2, 999, 3, 4) while x < 5]
I agree that the syntax is confusing.
The comprehension encourages thinking in sets: an operation that takes a
collection as input, and emits a different collection, through one
Adding ‘while’ in there encourages thinking not in terms of a single
set-based operation, but an iteration of separate operations. That
confuses the model, and I no longer have a coherent model about which to
reason what the syntax might mean.
> For comparison, what would you expect this to return? (Without
> actually trying it, thank you.)
> [x + 1 for x in (0, 1, 2, 999, 3, 4) if x < 5]
Though ‘for’ is used elsewhere in Python to mean iteration, ‘for’ also
has strong connotation in mathematics for set-based operations (“the
result is foo for all bar, if baz”). So the same confusion doesn't
occur: this is a comprehension which is about set-based thinking, which
is supported by all the semantic connotations of the syntax.
So I think ‘while’ should not be added to the syntax of comprehension
expressions. I agree with those who think it is not obvious what it
\ “I love to go down to the schoolyard and watch all the little |
`\ children jump up and down and run around yelling and screaming. |
_o__) They don't know I'm only using blanks.” —Emo Philips |