
On Sat, 5 Mar 2022 at 22:22, Stephen J. Turnbull <stephenjturnbull@gmail.com> wrote:
Chris Angelico writes:
What Python needs is not a way to cram more onto one line. What Python needs is a way to express an abstract concept: "iterate over the interesting parts of this collection".
Python has one, and you've already mentioned it:
for thing in (x for x in this_collection if is_interesting(x)):
It's noticably verbose, but it's an exact translation of your statement of the abstract concept above. It has all the benefits of the proposed syntax except compactness[1].
It is extremely verbose, considering that the filtering part of a comprehension uses the same variable name as iteration, doesn't need anything to be repeated, and is just another clause. A simple representation of that in a statement loop would be "for thing in this_collection if is_interesting(thing):", which doesn't repeat itself at all (the variable name "thing" is kinda essential to the concept of filtration here, so I don't count that); and repetition isn't simply about number of characters on the line, it's about reducing the potential for errors. (Plus, the genexp adds a significant amount of run-time overhead.) So you're right, I stand (partly) corrected: there IS a very clunky way to spell this concept. What Python needs is a non-clunky way to express this. ChrisA