Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically growing lists in Python

Tags:

python

list

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!

like image 293
Anonymous Avatar asked Dec 28 '10 08:12

Anonymous


People also ask

How do you create an automatic list in Python?

Use List Comprehension & range() to create a list of lists. Using Python's range() function, we can generate a sequence of numbers from 0 to n-1 and for each element in the sequence create & append a sub-list to the main list using List Comprehension i.e. It proves that all sub lists have different Identities.

How does Python increase list size?

The . extend() method increases the length of the list by the number of elements that are provided to the method, so if you want to add multiple elements to the list, you can use this method.

How do you extend multiple lists in Python?

Using + operator to append multiple lists at once This can be easily done using the plus operator as it does the element addition at the back of the list.


2 Answers

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]
like image 69
dan_waterworth Avatar answered Sep 20 '22 16:09

dan_waterworth


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.

like image 39
Senthil Kumaran Avatar answered Sep 18 '22 16:09

Senthil Kumaran