[Python-3000] else-clause on for-loops
Steven Bethard
steven.bethard at gmail.com
Fri Mar 24 19:11:37 CET 2006
On 3/24/06, Tim Peters <tim.peters at gmail.com> wrote:
> [Nicola Larosa]
> > ... I sometimes may have had a need for the current semantics
> > of the else after loops, but I don't remember it; on the other hand, I have
> > had a use for the no-iteration case a number of times. Somehow I find it
> > hard to stick into my mind that's not what it means.
>
> The primary use case is "search loops".
>
> for item in sequence:
> if desirable(item):
> break
> else:
> no desirable item exists
>
> Just remember "search loop", and you'll never be surprised again.
Yep, that's what I use 'em for. Of course once you drink that
Kool-Aid too often, you start wanting to write things like:
for item in seq:
for subitem in item:
if desirable(subitem):
break
else:
continue
break
else:
print 'no subsequences contain a desirable item'
It's about that time that I just refactor it to a function and replace
all those funny breaks and else-clauses with a simple return
statement.
STeVe
--
Grammar am for people who can't think for myself.
--- Bucky Katt, Get Fuzzy
More information about the Python-3000
mailing list