[Tutor] Strengths & weaknesses of Python lists compared to "old school" arrays [Was "Fixed Vector Array"]

Alan Gauld alan.gauld at btinternet.com
Thu Mar 5 14:26:53 CET 2015


On 05/03/15 12:20, Steven D'Aprano wrote:

>>> index position. In other words does the array need to be filled
>>> in a sequential manner or could you have a 'hole' in the middle...
>
> I'm not really sure that arrays can have holes in them. Basic low-level
> arrays, like found in Pascal, C or Fortran, cannot.

They can in the sense that I originally meant:
You declare the array and at compile time a block of memory
is reserved but it contains random trash, they are not usually 
pre-filled with, say zero. (Actually, Pascal may well do that,
it sounds like the kind of thing Pascal would do...)

You can then allocate values to any index within that array,
you don't need to do it sequentially as with a python list

You can fake it in Python by filling the array with a null
value such as zero or None but it takes explicit action and
run time resources to do that, unlike the C/Pascal equivalent.
Alternatively just use a dict.

> means of creating so-called "sparse arrays",

I wasn't really thinking of sparse arrays in the pure CS sense,
just a regular C array which does not necessarily have a
specified value at certain positions.

// file: openarray.c
#include <stdio.h>

void main(){
	static int ia[10];

	ia[0] = 3;
	ia[9] = 42;

	printf("array = %d,%d\n",ia[0],ia[9]);
	printf("splat! %d\n",ia[4]);
}

$ make openarray
$ ./openarray
array = 3,42
splat! 4195696

You can of course also initialize to zero by making it a
static array, but that has other consequences that you
may not want.

Hopefully that clarifies what I was thinking about.

Also I should add that this behaviour is rarely a
"Good Thing". Uninitialized values are usually
to be avoided!


PS.
Totally off topic but...
I just checked Pascal - boy am I rusty!

program openarray;

var ia : array[0..9] of integer;

begin
   ia[0] := 3;
   ia[9] := 42;

   writeln('array holds ', ia[0],' and ', ia[9]);
   writeln('splat - ',ia[4]);
end.

$ fpc openarray.pas
$ ./openarray
array holds 3 and 42
splat - 0

So yes it does fill with zeros. Thank you Nicholas...


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list