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!
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]
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.
No, but you could use a dictionary (hash table) to achieve the same thing.