list() coercion

Raymond Hettinger vze4rx4y at verizon.net
Thu Jul 17 11:08:16 EDT 2003


"Ian Bicking" <ianb at colorstudy.com> wrote in message
news:mailman.1058400718.22076.python-list at python.org...
> I have an iterable object.  It supports many list-like methods,
> specifically __len__.  These methods are rather expensive (they result
> in database calls, COUNT(*) to be specific), but cheaper than iterating
> over the object.  Sometimes it is useful to create a list from the
> iterator, using list().  However, list() seems to call the object's
> __len__, I imagine to pre-allocate space.  This is a problem, as
> pre-allocation saves much less than is spent doing __len__.
>
> Is there a way I can keep this from happening?  Maybe something list()
> tries first that I can make fail.  (I notice list() catches any
> exceptions in __len__ and then will just skip that step)

Instead of:

    list(yourobj)

use:

    list(iter(yourobj))

If that doesn't help, create your own wrapper:

def myiter(it):
    for elem in it:
        yield it

list(myiter(yourobj))


This idea is to provide 'list' with a wrapper that only supplies
the iter methods and not the len method.


Raymond Hettinger






More information about the Python-list mailing list