Array design question

Dave Benjamin ramen at lackingtalent.com
Fri May 30 13:29:56 EDT 2003


In article <GA-dnfOXAroprUujXTWcpg at comcast.com>, Terry Reedy wrote:
>> I just don't understand, why Python doesn't allow to exceed array
>> boundaries. PHP and Perl would resize the array in this case.
> ...
>> Is there any reason why Python designers chose this concept?
> 
> 1) The way seqs are intended to be used, indexing out-of-bounds is
> often an error which should be caught.  Wanting auto extension is
> unsual.
>
> ...

Just to clarify here, PHP does not "auto-extend". It leaves gaps. If I say:

$a[0] = 1;
$a[1000] = 2;

I get:

$a == array(0 => 1, 1000 => 2)

In other words, it behaves like a Python dict, not a list. With one
noticeable difference: PHP "arrays" are ordered, and the ordering is based
on the insertion pattern. See my recipe on ASPN for an example of how to get
the same effect in Python:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747

Note that there are a few other differences with PHP. For one, arrays are
"auto-vivified" - they spring to life as soon as you assign to an item:

unset($a);
$a[5] = 6; // $a == array(5 => 6)

This behavor can lead to bugs, and I much prefer Python's safety in this
regard. However, it does come in handy sometimes. Python has no equivalent
(to my knowledge) of this:

$a = array();
...
$a[0][2] = 'hello';
...
$a[1][3] = 'world';

Python would make you do this:

a = {}
...
a.setdefault(0, {})
a[0][2] = 'hello'
...
a.setdefault(1, {})
a[1][3] = 'world'

In other words, PHP will actually create nested arrays (I'm using the term
"array" in the PHP sense) on the fly if you use multiple indexes. You could
say:

$a[0][0][0][0] = 'ramen';

And you'd actually get a quadruply-nested array. Even if $a doesn't exist.

Dave




More information about the Python-list mailing list