Implicit lists

Alex Martelli aleax at aleax.it
Fri Jan 31 15:09:56 EST 2003


Donnal Walter wrote:
  ...
> don't understand is how does one determine if they are empty or not?
> 
>     def __init__(self, ref=[]):
>         self.__ref = iteron(ref)
>         if len(self.__ref) > 0:
>             # do something
> 
> produces TypeError: len() of unsized object

The ONLY way you can use a generator is by looping on it (normally
with a for statement, though you may choose to explicitly call
.next() and check for StopIteration being raised -- or, have the
loop be done implicitly for you from builtin functions).

Looping on a generator "consumes" it, so you get to do it only
once.  If you need to loop more than once, you can build a list:

         self.__ref = list(iteron(ref))


Of course, this will consume (potentially) a lot of memory.

To check the number of items in a generator, you basically
need to loop on the generator (you could think of tricks
based on wrapping the generator just to determine if it's
empty or not, but while clever they're unlikely to be worth
it) and thus here you may want to turn it into a list.


Alex





More information about the Python-list mailing list