recognizing empty iterators

Bengt Richter bokr at oz.net
Wed Jul 23 00:41:18 EDT 2003


On Tue, 22 Jul 2003 16:41:29 -0600, Steven Taschuk <staschuk at telusplanet.net> wrote:

>Quoth Michele Simionato:
>> Steven Taschuk <staschuk at telusplanet.net> wrote in message news:<mailman.1058835583.22488.python-list at python.org>...
>  [...]
>> > I don't have anything substantial to add to others' posts, but I
>> > wonder: under what circumstances do you want to do this?
>> 
>> I wanted to check the output of ifilter or imap; [...]
>
>Ah.  And then, if there were elements in the iterator, I assume
>you would then process them somehow, right?  Why not just do that
>with a for loop, say, and check afterwards whether anything has
>been done?  A silly example:
>
>    processed = 0
>    for x in iterator:
>        process(x)
>        processed = processed + 1
>    if processed:
>        # ...
>
You can avoid flag bumping in the loop:

 >>> x = object(); idx=id(x)
 >>> for x in iter(''): print x,
 ...
 >>> id(x)==idx
 1
 >>> for x in iter('abcd'): print x,
 ...
 a b c d
 >>> id(x)==idx
 0

Regards,
Bengt Richter




More information about the Python-list mailing list