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:
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