
On Tue, Jun 29, 2021 at 5:04 PM Steven D'Aprano <steve@pearwood.info> wrote:
On Tue, Jun 29, 2021 at 01:37:59AM +0100, Rob Cliffe via Python-ideas wrote:
for i in range(0, 10): if i not in range(2, 8): <do stuff> # This is arguably slightly easier to read than having two separate lines,
"Arguably" is an understatement.
as it puts both aspects of a single concept ("what values of i do I loop over?") together.
I would consider it two concepts: (1) you're looping over the values range(0, 10) and (2) skipping over values in range(2, 8).
What if you loop over the values in the range(0, 10) but skip all of the odd numbers? Is that two concepts too? Because we have an easy way to spell that: range(0, 10, 2). Why should a disjointed range be fundamentally different? It's one concept: looping over all the values from 0 to 10 that aren't between 2 and 8.
Until we reach the bottom of the block, we can't be sure that the condition isn't
if i not in range(2, 8): ... else: ...
which by the way suggests that this suggested syntax would be ambiguous:
Do you have this problem with comprehensions? No. Why not? Because you can't put an "else" when you're using "if" to filter a condition. Seems pretty straight-forward to me. I do think that filtering would be a useful feature to have, but for ranges, the best way IMO is to change the thing you're iterating over. It's not that hard to devise a range-like object that supports subtraction; I whipped up a quick demo above. You could make it possible to subtract one range from another, or whatever suits your purpose, and ultimately, you'd still end up with the basic "for value in iterable:" syntax, just with a more detailed iterable. ChrisA