recognizing empty iterators

Steven Taschuk staschuk at telusplanet.net
Wed Jul 23 00:41:29 CEST 2003


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:
        # ...

> [...] at the end I solved
> my problem in another way, nevertheless I am surprised there is no
> way to check for an empty iterator in current Python, it seems to be
> a quite legitimate question, isn't it?

Absolutely.  I was just curious what the original problem was.

(I haven't read the iterators PEP in a while, but it seems to me
the iterator protocol is deliberately minimalistic.  Makes it
easier to write them; and if you do frequently need lookahead,
writing a wrapper as others have suggested seems easy enough.)

-- 
Steven Taschuk             "The world will end if you get this wrong."
staschuk at telusplanet.net     -- "Typesetting Mathematics -- User's Guide",
                                 Brian Kernighan and Lorrinda Cherry





More information about the Python-list mailing list