The thing is, if block is more than a couple lines, you need to look down to see if there’s an else or any number of elif blocks down there— so this isn’t a clear expression of a filtered iteration after all. Which is why I suggested that:
for item in items:
if not condition:
Would be the more direct expression of "filtered iteration" -- still not a whole lot of code, but a bit more awkward.
The other thing that I think is relevant is that comprehensions already have a filtering option -- so while new syntax technically. this proposal would be familiar and create a bit more consistency in the language.
Another half formed idea:
Comprehension can express map-like behavior or map and filter behavior, but no way to filter without a do nothing map.
e.g if you want to only filter, you need to do:
(item for item in items if condition)
I wonder if there's a way to not need to the "item for item" wasted text:
(Item in items if condition)
[item in items if condition]
it's not legal syntax now. That would then allow:
for item in (item in items if condition):
which is almost what's being asked for here. But then the repetition again.
Which leads us back to the OP’s proposal.
I’m actually liking that more now ….
Christopher Barker, PhD (Chris)
Python Language Consulting
- Scientific Software Development
- Desktop GUI and Web Development
- wxPython, numpy, scipy, Cython