Alex Rivera | Logout

better for-loop syntax for detecting empty sequences?

Asked 2010-12-29T19:42:14.797
11

Is there a better way to write the following:

   row_counter = 0
   for item in iterable_sequence:
      # do stuff with the item

      counter += 1

   if not row_counter:
      # handle the empty-sequence-case

Please keep in mind that I can't use len(iterable_sequence) because 1) not all sequences have known lengths; 2) in some cases calling len() may trigger loading of the sequence's items into memory (as the case would be with sql query results).

The reason I ask is that I'm simply curious if there is a way to make above more concise and idiomatic. What I'm looking for is along the lines of:

for item in sequence:
   #process item
*else*:
   #handle the empty sequence case

(assuming "else" here worked only on empty sequences, which I know it doesn't)

Edit
Report

1 Answer

0
if not iterable_sequence.__length_hint__():
    empty()
else:
    for item in iterable_sequence:
        dostuff()
answered 2010-12-29T19:48:48.353

Your Answer