Dynamically expand python array when assigned to it

I want to populate an array in python so that I can use id numbers to index into an array. Not all indexes will exist in the array, and elements will not necessarily be added to the array in order. The largest possible index is unknown (or at least I would rather not hard code it). Is there a way to dynamically grow an array on assignment? I want something like

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

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

Is there a good way to do this in python, or do I need to decide to initialize an array "large enough"?

+7
python
source share
4 answers

You will need dictionary

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

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

 myDict = {x.index:x for x in xs} 
+7
source share

Just use arr.append(x) to add items.

0
source share

Why aren't you trying to add a list?

 arr = [] for x in xs arr.append(x) 

then refer to arr as: arr [0], arr [1], etc.

0
source share

Python arrays can grow dynamically, but simply assigning an index does not expand the array.

Arrays have an extend method to add multiple elements to the collection at once. For example:

 >>> a = [1, 2, 3] >>> a.extend([None, None]) >>> a [1, 2, 3, None, None] 

You can emulate automatic array expansion as follows:

 def arr_assign(arr, key, val): try: arr[key] = val return except IndexError: # Do not extend the array for negative indices # That is ridiculously counterintuitive assert key >= 0 arr.extend(((key + 1) - len(arr)) * [None]) arr[key] = val return 

For example:

 >>> a = [] >>> arr_assign(a, 4, 5) >>> a [None, None, None, None, 5] 

As an addition, languages ​​that by default have auto-expansion behavior (e.g. Perl, Ruby, PHP, JavaScript, Lua) tend to be less strict than Python, and return a magic null value if you access the slot in an array, which does not exist. This means that they can allow automatic expansion when assigning a nonexistent index without changing the behavior of the array in any other index.

eg. In Ruby, a[2] does not change, even though a has changed under it.

 irb(main):006:0> a = [] => [] irb(main):007:0> a[2] => nil irb(main):008:0> a[4] = 7 => 7 irb(main):009:0> a => [nil, nil, nil, nil, 7] irb(main):010:0> a[2] => nil 
0
source share

All Articles