Live data from Hacker News

The optional “else” in Python loops

shahriar.svbtle.com

31–40 of 50 posts

Re: The optional “else” in Python loops

#31
post #25
post #2

While in theory this is useful, it's one of the least intuitive parts of python for me. I avoid them whenever possible because I feel "else" conveys the intent very poorly. (And I've been writing python for years.)

What's more, it dances very close to something that is a super-common error for novice programmers: the early return from a loop. I grade AP exams every year, and one of the hands-down most common conceptual mistakes I've seen (on problems where this is relevant) goes something like this: boolean lookForSomething(int parameter) { for (Item item: list) { if (item.matches(parameter)) return true; else return false; } }…

That last one is not idiomatic (I’ll ignore the lowercase first letter of True and False).

The `else` there is superfluous; that cuts it down to this:

    def look_for_something(parameter):
        for item in list:
            if matches(item, parameter):
                return True
        return False
And then after that one should just replace the entire loop with an `any` call:

    def look_for_something(parameter):
        return any(matches(item, parameter) for item in list)
Also, if we assume a `matches()` that is simple equality, then it would just be

    def look_for_something(parameter):
        return parameter in list
… and even then, you shouldn’t have named a variable `list`.

Cut down to its essence like this, the function probably shouldn’t have even existed… ☺

Re: The optional “else” in Python loops

#32
post #28

Earlier quoted context omitted.

What about using "finally," which if IIRC is already a thing in Python and encapsulates this idea pretty neatly?

finally blocks are always executed; this kind of else block is only executed if the for block exited normally (i.e. did not throw an exception).

How about a keyword such as "after"? I feel like that could have extensible potential in other areas of the language, and the name makes a little sense logically speaking.

Re: The optional “else” in Python loops

#33
post #20
post #12

Raymond Hettinger, one of the main Python devs, advises that the "else" in this situation should mentally be thought of as "notfound".

Glad you posted this. I came to the comments to post the same thing[1] because thinking of it as "notfound" makes remembering (and comprehending it) easier. :) [1] https://www.youtube.com/watch?v=OSGv2VnC0go#t=17m12s

Ah, I misremembered, "nobreak", not "notfound".

Re: The optional “else” in Python loops

#37
post #24
post #7

Earlier quoted context omitted.

What finally made it intuitive for me: assuming the loop contains an if condition: break, you can consider the else-clause to be the else of the if statement within the loop.

I think the real issue is that the word 'else' is ambiguous in the context. Everyone comes in with a different idea of what the 'else' is a fallback clause to. Guido obviously picked one particular case, but there are other valid meanings. For example, I think that it's more common to want to do something like: # mnemonic: # for thing in list_of_things DO_SOMETHING else DO_SOMETHING_ELSE if list_of_things: for thing…

That makes sense on one level, but when you consider Pythons indenting rules, it just messes everything up.

Re: The optional “else” in Python loops

#38
post #15

I always strongly discourage the use of things like this construct in any language. A language is meant to be read not just written. A non-expert python programmer who encounters this will be confused.

There will always be non-expert programmers of many languages. Avoiding language-specific constructs will not solve the issue. As far as portability is concerned (if you port software by hand a lot, for example), this is indeed an issue; but if you work with people who write python code, you might as well use everything in your toolbox.

As someone who did years of Perl (and that's not the most intuitive of languages), I was really confused when I first saw this in Python.

Re: The optional “else” in Python loops

#39
post #16

I always strongly discourage the use of things like this construct in any language. A language is meant to be read not just written. A non-expert python programmer who encounters this will be confused.

> who encounters this will be confused And get it after 30 seconds doc reading?

After 2 hours of searching to find the appropriate piece of documentation.

I encountered this situation. I assumed the else belonged to an if, but the indentation rules were somehow being broken. What would you expect me to look up in the docs?

Re: The optional “else” in Python loops

#40
post #25

Earlier quoted context omitted.

What's more, it dances very close to something that is a super-common error for novice programmers: the early return from a loop. I grade AP exams every year, and one of the hands-down most common conceptual mistakes I've seen (on problems where this is relevant) goes something like this: boolean lookForSomething(int parameter) { for (Item item: list) { if (item.matches(parameter)) return true; else return false; } }…

That last one is not idiomatic (I’ll ignore the lowercase first letter of True and False). The `else` there is superfluous; that cuts it down to this: def look_for_something(parameter): for item in list: if matches(item, parameter): return True return False And then after that one should just replace the entire loop with an `any` call: def look_for_something(parameter): return any(matches(item, parameter) for item in…

Remember that I was talking about novice programmers, here. I'll concede that "idiomatic" was a bit strong (and the True/False thing was a brain fart), but I think my main point stands: encouraging the use of an "else:" that can attach to loops, with an unobvious and somewhat nuanced semantics, is not kind to newcomers. And the fact remains that the difference between a correct implementation and one that is wrong in exactly the way that a lot of newcomers get it wrong is nothing but indentation.
Post reply on HN