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!
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With