else: does not trigger when there is no data on which to iterate, but
when the loop terminated normally (ie., wasn't break-ed out). It is
meaningless without break.
The else clause *is* executed when there is no data on which to iterate.
Your example even demonstrates that clearly:
Your example even demonstrates that clearly:
>>> for x in []:
... print 'nothing'
... else:
... print 'done'
...
done
I agree that it is meaningless without a break statement, but I still find it useful when I want to determine whether I looped over the whole list or not. For example, if I want to see whether or not a list contains an odd number:
for i in list:
if i % 2 == 1:
print "Found an odd number."
break
else:
print "No odd number found."
Without the else clause I would need to use an extra variable as a "flag" and check its value outside the loop:
found = False
for i in list:
if i % 2 == 1:
print "Found an odd number."
found = True
break
if not found:
print "No odd number found."
OK, so using "else" only saves me 2 lines and a variable - not much to write home about, but I still like it.
Johan.
-- http://mail.python.org/mailman/listinfo/python-list