1
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!

1
  • 2
    use dict: testDict={} instead. Commented Jun 13, 2019 at 19:57

2 Answers 2

5

Perhaps you need a dict:

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

print(testList)
print(testList[23])

Output:

{12: 31, 23: 1337}
1337
Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.