3 ms·
I've been using this for years and never thought twice about it, I'm shocked by all the negativity. It's great for controlling iteration in a nested loop: f
by jacob019 8y ago
I've been using this for years and never thought twice about it, I'm shocked by all the negativity.
It's great for controlling iteration in a nested loop:
for item in report():
for event in in item['events']:
if event in events_we_care_about:
break
else:
continue
act_upon(item)
I realize it's a trivial example that could be written without a nested loop, but there are often good reasons for nested loops and littering them with control variables and if statements gets messy quick. I have always found for-else to produce more elegant code.
Your criticisms may be quite valid, I just wanted to share my surprise.
- ankrgyl 8y agoI may be missing something... but how is that clearer than for item in report(): for event in item['events']: if event in events_we_care_about: act_upon(event) break
- jacob019 8y agoIt's a trivial example. Just to demonstrate how for else helps to control an outer loop from within an inner loop.
- rahimnathwani 8y agoYour act_upon is passed values from the inner loop. GP's act_upon is passed values from the outer loop.
- Asooka 8y agoI would write that as for item in report(): if any(event in events_we_care_about for event in item['events']): act_upon(item) But obviously the features that enable this form didn't exist when for...else was added to the language.
- jacob019 8y agoClearly it was a poor example, I wouldn't structure simple code this way either but in more complex situations it can be the simplest solution.