Dynamically growing a python array when assigning to it

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}

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

Arrays have the extend method for adding a bunch of items at once from a collection. For example:

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

You can emulate auto-extending array assignment like this:

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 addendum, languages that do have the auto-extend behavior by default (e.g. Perl, Ruby, PHP, JavaScript, Lua) tend to be less strict than Python and will return a magical null value if you access a slot in an array that doesn't exist. This means that they can allow auto-extending when assigning to a non-existent index without changing the behavior of the array at any other index.

E.g. In Ruby a[2] doesn't change despite the fact that a has changed underneath 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

Tags:

Python