For - else clause

The proposed for/else construct in pseudo code reads as follows:

For item in items:
Do something
If the loop was empty:
Do something else

Notice how the “else” really means “if the loop is empty”. IMO the clearest way to say “if the loop is empty” is an if-statement. Every time a reader came to a for/each, they would have to understand it in their head to mean an if-statement.

The for/else construct is made even more confusing as Python already uses it to mean “if the loop iteration completed without error”. To be fair, python’s interpretation is just as natural as the proposed one here.

The benefit to adding for/else is small. The biggest benefit is “better readability” but it’s arguably harder to read than an explicitly written if (it.isEmpty()) { /* ... */ }. Even if it was unquestionably more readable with for/else, it doesn’t have a strong impact to warrant much priority or added maintenance.

Maybe there’s an alternative languages change that would be more impactful? For example, having loops be expressions instead of statements? That proposal would enable OPs exact request on a language level and potential support a lot more. (I’m not advocating for that, just wanted to point out that there are other ways to get this feature)

4 Likes