marie1995
marie1995

Reputation: 59

Create List with variable length in Python

testList= []
testList[12]= 31
testList[23]= 1337

Error: IndexError: list assignment index out of range

Basically I have unique Integers and I want to use the lists for a hash function h(x)= x (because they are unique)

I could initialize the length like this:

testList= [0 for i in range(50)]

But then I have to fix the size and my unique numbers which I have increase with time. Is it ok to set the size to for example 1-2Mio or is there a way to do this dynamically? ArrayList<> in Java is dynamically for append and delete but so are Lists in Python also.

Thanks!

Upvotes: 1

Views: 8412

Answers (2)

Alain T.
Alain T.

Reputation: 42143

If you don't want to use a dictionary (which I do think you should do), you could create your own auto-extensible list:

class defaultlist(list):

    def __init__(self,defData):
        self.defData = defData

    def _getDefault(self):
        if isinstance(self.defData,type):
            return self.defData()
        return self.defData

    def __getitem__(self,index):
        if index >= len(self):
            return self._getDefault()
        return super.__getitem__(index)

    def __setitem__(self,index,value):
        while index>=len(self):
            self.append(self._getDefault())
        list.__setitem__(self,index,value)


testList = defaultlist(0) # need to provide a default value for auto-created items
testList[12]= 31
testList[23]= 1337

print(testList)
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1337]

Upvotes: 0

quamrana
quamrana

Reputation: 39354

Perhaps you need a dict:

testList = {}
testList[12]= 31
testList[23]= 1337

print(testList)
print(testList[23])

Output:

{12: 31, 23: 1337}
1337

Upvotes: 5

Related Questions