dumb newbie list question

Alex Martelli aleaxit at yahoo.com
Mon Aug 20 05:15:33 EDT 2001


"Dietmar Lang" <dietmar at wohnheim.fh-wedel.de> wrote in message
news:3B80427F.53E233FB at wohnheim.fh-wedel.de...
>
> Hi!
>
> > Maybe this is a naive/stupid question, but is there anyway to grow a
list to an
> > arbitrary size?  Eg.:
> >
> > >>> l = [1, 2, 3]
> > >>> l[5] = "x"
>
> I believe l.append("x") ist what you're looking for.

That would make l[3] be 'x', rather than l[5] as the original poster
asks.  To get 'x' into l[5], something must be placed in l[3] and
l[4] as well, e.g.:

def set_extending(alist, index, value, default=None):
    extras = index - len(alist)
    if extras >= 0:
        alist.extend(extras*[default]+[value])
    else:
        alist[index] = value

Now set_extending(l, 5, 'x') would work as desired.  One might
use this idea in the __setitem__ method of a UserList, or, in
Python 2.2, in that of a class that inherists from list.


Alex






More information about the Python-list mailing list