Jumping around when assigning elements

Peter Otten __peter__ at web.de
Mon Dec 15 19:22:25 EST 2003


Matthew Sims wrote:

> Is there anyway to assign to an element that wasn't defined in the
> beginning? Like if I wanted element 5 assigned but not element 4
> without using "" or None?

You can write your own class:

class GrowingList(list):
    def __init__(self, seq, default=None):
        list.__init__(self, seq)
        self.default = default
    def __setitem__(self, index, value):
        if index >= len(self):
            self.extend([self.default]*(index - len(self)))
            self.append(value)
        else:
            list.__setitem__(self, index, value)


g = GrowingList(["alpha", "beta", "gamma"])
g[7] = "omega"
print g

This is a partial implementation, only g[index] = value will work.

> I'm currently re-writing a Perl script into Python and with Perl I was
> free to assign any element in the array without having to fill in the
> previous elements. I can't seem to do that in Python...unless I'm
> doing it wrong.

As already pointed out, a mechanical translation will yield substandard
results. As you did not describe the problem you are solving with the
"autogrowing" list, there is little chance for us to come up with a better
or at least more idiomatic approach.

Peter

PS: Welcome to the worst programming language - except all others :-)










More information about the Python-list mailing list