Is there a way to make an automatically growing list in Python? What I mean is to make a list that would grow when an index that does not yet exist is referenced. Basically the behaviour of Ruby arrays.
Thanks in advance!
Sure it's possible, you just have to use a subclass of list to do it.
class GrowingList(list):
def __setitem__(self, index, value):
if index >= len(self):
self.extend([None]*(index + 1 - len(self)))
list.__setitem__(self, index, value)
Usage:
>>> grow = GrowingList()
>>> grow[10] = 4
>>> len(grow)
11
>>> grow
[None, None, None, None, None, None, None, None, None, None, 4]
__setitem__ is a special method, it's not often called via it's name, but like in the example grow[10] = 4.__init__ function, but that wouldn't play well with being inherited from list, you'd need to change the __new__ method, but I'm just trying to write a simple example.Lists are dynamic in python. It will automatically grow always (up until you hit sys.maxsize) in your program.
l = list()
l.append(item)
Keep doing that.
a[3] to a[99] be after this?nil; in Python, None would be the logical choice.No, but you could use a dictionary (hash table) to achieve the same thing.
Noneor some other default value?a[1000]if it doesn't exist yet?IndexErroror should the list grow to this size, too?