Jumping around when assigning elements
__peter__ at web.de
Tue Dec 16 01:22:25 CET 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:
def __init__(self, seq, default=None):
self.default = default
def __setitem__(self, index, value):
if index >= len(self):
self.extend([self.default]*(index - len(self)))
list.__setitem__(self, index, value)
g = GrowingList(["alpha", "beta", "gamma"])
g = "omega"
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.
PS: Welcome to the worst programming language - except all others :-)
More information about the Python-list