🎙️
11

Was reading through the Python docs and found out you can use an else block on a for loop...

I've been working through this online course for about 2 weeks now, just basic stuff. I was looking up how to handle loops and stumbled on this in the official Python tutorial. You can put an 'else' after a 'for' or 'while' loop and it only runs if the loop didn't hit a 'break'. I had no idea that was even a thing. Has anyone else used this in a real project or is it one of those obscure features nobody actually needs?
4 comments

Log in to join the discussion

Log In
4 Comments
cameronjenkins
cameronjenkins28d agoMost Upvoted
The else clause doesn't actually care if the loop hit a break, it runs when the loop condition becomes false naturally. So if you have a for loop over a list and it finishes all items without breaking, the else runs. But if you break out early, the else gets skipped. It's a common mix up because the doc example makes it look like a reward for not breaking. I've used it once in a script where I needed to know if a search pattern found anything without keeping a flag variable. Worked fine but it confused everyone who read my code later.
8
jenkins.reese
Stick with a simple flag variable and save yourself the headache. I learned that lesson the hard way when someone on my team spent two hours trying to debug why an else clause in a for loop was causing weird behavior. Ended up rewriting the whole thing with a boolean flag and it worked perfectly, took five minutes. The point @cameronjenkins makes about confusing everyone later is exactly why I stopped using it. If you need to know if a search succeeded, just use a flag variable like "found = False" and flip it to True when you hit the condition, then check that after the loop. Nobody has to scratch their head over what your code does.
3
jamiew53
jamiew5322d ago
Exactly, team maintenance is way more important than flexing your Python knowledge.
6
chen.adam
chen.adam28d ago
Right, the whole "confused everyone who read my code later" part is exactly what I was thinking. I mean, are you writing code for the next person or just trying to be clever? It's like you're setting a trap for some poor soul who's just trying to fix a bug at 2 AM and suddenly has to figure out why an 'else' is running after a loop finished. I've seen this feature described as "pythonic" but honestly it feels more like a prank the creators played on us. The doc example does make it look like a reward for not breaking, which is just adding fuel to the fire. Maybe it's just me, but I'd rather just use a flag variable and not have to explain my code to every new team member who looks at it.
4