this post was submitted on 04 Feb 2025
171 points (93.8% liked)
Programmer Humor
20351 readers
2086 users here now
Welcome to Programmer Humor!
This is a place where you can post jokes, memes, humor, etc. related to programming!
For sharing awful code theres also Programming Horror.
Rules
- Keep content in english
- No advertisements
- Posts must be related to programming or programmer topics
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
Did you know python for loops have an else clause?
Did you also know it runs after the loop iterator is done, and not when there was never anything to iterate over at all?
https://docs.python.org/3/reference/compound_stmts.html#for
That actually seemed quite useful at first.
Your point about it not running when there is nothing to iterate over is incorrect. The else-statement runs when the iterator is exhausted; if the iterator empty, it is exhausted immediately and the else-statement is executed.
I think it's intended as "not only when" because it would make sense to have an "if empty" case but the way it is, it doesn't make sense
I think it does make sense, it's a "did this loop exit naturally? If so, do x". This makes a lot of sense if you, for example, have a loop that checks a condition and breaks if that condition is met, e.g. finding the next item in a list. This allows for the else statement to set some default value to indicate that no match was found.
Imo, the feature can be very useful under certain circumstances, but the syntax is very confusing, and thus it's almost never a good idea to actually use it in code, since it decreases readability a lot for people not intimately familiar with the language.
Edit: Now, this is just guessing, but what I assume happens under the hood is that the else statement is executed when the StopIteration exception is recieved, which happens when next() is called on an exhausted iterator (either empty or fully consumed)
Couldn't you just handle this with:
Thinking about it, it totally makes sense and has in inherent logic, even tho it's not intuitive