After reading Automatically growing lists in Python, I'm now attempting to create an automatically growing 2 dimensional list. Basically I would say
>>> l = 2DGrowingList(' ') # Fills the inner lists with space (' ') character
>>> l[1][2] = 'x'
>>> print(l)
[[], [' ', ' ', 'x']]
>>> l[0][1] = 'a'
>>> print(l)
[[' ', 'a'], [' ', ' ', 'x']]
What I attempted was this:
class GrowingList(list):
def __init__(self, fill):
super().__init__()
self.fill = fill
def __setitem__(self, index, value):
if index > len(self) - 1:
self.extend([self.fill] * (index + 1 - len(self)))
list.__setitem__(self, index, value)
Now I tried to create a new 2D list like so:
l = GrowingList(GrowingList(' '))
But it doesn't work as intented, since it uses the same instance for filling the lists:
>>> l[3][0] = 'x'
>>> print(l)
[[], [], [], ['x']]
>>> l[1][0] = 'y'
>>> print(l)
[['y'], ['y'], ['y'], 'x']
Besides, it doesn't allow me to use l[0][2] = ...
instantly, but I must first call l[0]
before I can access l[0][2]