Rick Johnson wrote: > On Feb 23, 6:30 pm, Alex Willmer <[email protected]> wrote: >> [...] >> as a standard looping-with-index construct. In Python for loops don't >> create a scope, so the loop variables are available afterward. I've >> sometimes used this to print or return a record count e.g. >> >> for i, x in enumerate(seq): >> # do stuff >> print 'Processed %i records' % i+1 > > You could employ the "else clause" of "for loops" to your advantage;
>>>> for x in []: > ... print x > ... else: > ... print 'Empty Iterable' > Empty Iterable > >>>> for i,o in enumerate([]): > ... print i, o > ... else: > ... print 'Empty Iterable' > Empty Iterable No: >>> for i in []: ... pass ... else: ... print "else" ... else >>> for i in [42]: ... pass ... else: ... print "else" ... else >>> for i in [42]: ... break ... else: ... print "else" ... >>> The code in the else suite executes only when the for loop is left via break. A non-empty iterable is required but not sufficient. -- http://mail.python.org/mailman/listinfo/python-list
