Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically growing a python array when assigning to it

Tags:

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"?

like image 367
tengfred Avatar asked Dec 13 '13 13:12

tengfred


People also ask

How do you assign an array dynamically?

dynamically allocated arrays To dynamically allocate space, use calls to malloc passing in the total number of bytes to allocate (always use the sizeof to get the size of a specific type). A single call to malloc allocates a contiguous chunk of heap space of the passed size.


1 Answers

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}
like image 170
thefourtheye Avatar answered Oct 01 '22 02:10

thefourtheye