better for-loop syntax for detecting empty sequences?

Posted by Dmitry Beransky on Stack Overflow See other posts from Stack Overflow or by Dmitry Beransky
Published on 2010-12-29T19:42:14Z Indexed on 2010/12/29 19:54 UTC
Read the original article Hit count: 207

Filed under:
|
|
|

Hi,

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)

© Stack Overflow or respective owner

Related posts about python

Related posts about syntax