1.5.2 for: else:

Greg Ewing greg.ewing at compaq.com
Wed Jul 28 16:51:15 EDT 1999


Gordon McMillan wrote:
> 
> But finding a match in a list, and testing whether you
> fell off the end without finding one, is (without the else clause) a
> much messier proposal.

Not if you go about it the right way. I always
put such loops in a procedure of their own,
and use return:

  def find_the_holy_grail(stuff):
    for x in stuff:
      if is_holy_grail(x):
        return x
    return None

Not only does this not require a weird else
clause, it doesn't require break either. I
almost never use break - and when I do I usually
regret it later. I wouldn't mind if there weren't
any break - and without break, there would be no
need for the weird else.

Greg




More information about the Python-list mailing list