Most efficient way to "pre-grow" a list?

gb345 gb345 at invalid.com
Sun Nov 8 10:20:42 EST 2009


In <mailman.44.1257626420.2873.python-list at python.org> Luis Alberto Zarrabeitia Gomez <kyrie at uh.cu> writes:

>¿Have you ever tried to read list/matrix that you know it is not sparse, but you
jdon't know the size, and it may not be in order? A "grow-able" array would just
>be the right thing to use - currently I have to settle with either hacking
>together my own grow-able array, or...
>...Not hard, not worthy of a
>PEP, but certainly not so easy to dismiss.



I'm pretty new to Python, and I thought I'd give this a try:

class array(list):
    """A list that grows as needed upon assignment.

    Any required padding is done with the value of the fill option.
    
    Attempts to retrieve an index greater than the maximum assigned
    index still produces an IndexError.
    """

    def __init__(self, seq='', fill=None):
        super(array, self).__init__(seq)
        self.fill = fill

    @property
    def max(self):
        return len(self) - 1

    def __setitem__(self, index, item):
        m = self.max
        while m < index:
            self.append(self.fill)
            m += 1
        super(array, self).__setitem__(index, item)

if __name__ == '__main__':
    x = array(('zero',))
    x[3] = 'it works!'
    print x

---------------------------------------------------------------------------
['zero', None, None, 'it works!']



Looks like it works, but it seems almost too easy.  Did I miss
anything?  Comments welcome.  (E.g.  I'm not sure that '' is the
best choice of default value for the seq parameter to __init__.)

Thanks in advance,

Gabe




More information about the Python-list mailing list