Anonymous
Anonymous

Reputation: 221

Automatically growing lists in Python

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!

Upvotes: 21

Views: 20406

Answers (3)

dan_waterworth
dan_waterworth

Reputation: 6441

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]

Upvotes: 47

Senthil Kumaran
Senthil Kumaran

Reputation: 56851

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.

Upvotes: 2

Keith
Keith

Reputation: 43024

No, but you could use a dictionary (hash table) to achieve the same thing.

Upvotes: -1

Related Questions