Python – Dynamically growing a python array when assigning to it

python

I want to populate an array in python so that I can use id numbers to index into the array. Not all indexes will exist in the array and items will not necessarily be added to the array in order. The largest possible index is not known (or at least I'd prefer not to hard code it). Is there a way to dynamically grow the array when assigning?
I.e I want something like

arr = []
for x in xs
    arr[x.index] = x

but this gives "IndexError: list assignment index out of range". I tried using list.insert() but that does not work if the items are not inserted in order, as it changes the index of items already in the array.

Is there a good way to do this in python, or do I have to settle for initializing the array "big enough"?

Best Answer

You need a dictionary

arr = {}
for x in xs:
    arr[x.index] = x

If all you are going to do is to build the dictionary, you can use dictionary comprehension like this

myDict = {x.index:x for x in xs}