for-else

Raymond Hettinger python at rcn.com
Tue Mar 4 21:09:45 CET 2008


[BearOphile]
> So far in Python I've almost hated the 'else' of the 'for' loops

FWIW, I'm very happy with for-else.  Most of the time, you don't need
it, but when you do, it beats the heck out of doing silly tricks with
flags.

The primary use case is searching a container:

   prep_tasks()
   for item in container:
       if predicate(item):
           found_tasks()
           break
   else:
       not_found_tasks()
   follow_up_tasks

Raymond



More information about the Python-list mailing list