Dynamically growing numarray array.

Robert Kern robert.kern at gmail.com
Wed Mar 22 21:51:45 CET 2006

Ivan Vinogradov wrote:
> Hello All,
> this seems like a trivial problem, but I just can't find an elegant  
> solution neither by myself, nor with google's help.
> I'd like to be able to keep an array representing coordinates for a  
> system of points.
> Since I'd like to operate on each point's coordinates individually,  
> for speed and ufuncs
> numarray fits the bill perfectly, especially since system.coordinates 
> [4] would return proper vector for a 5th point.

BTW, numpy is replacing numarray, so if you're just getting started, you will
probably want to be using numpy.


> To start, read the coordinates from a text file and add them to our  
> array one by one.
> Here it gets un-elegant and probably wasteful for a large number of  
> points, by converting the whole array to a list only to use append  
> method and then convert it back to array(sample code below). Also,  
> there is potential need to add more points later on.

Well, you can accumulate points in a list, and them concatenate them wholesale
when you are done. Something like the following (untested):

  import numpy
  a1 = ... # some pre-existing array of points
  f = open('mypoints.txt')
  newpoints = []
  for point in points_from_file(f):
  a1 = numpy.vstack((a1, newpoints))

Doing the "a1 = numpy.vstack(...)" for each point is rather slow.

numpy arrays do have a .resize() method, but it's not very safe and probably
just as slow as doing numpy.vstack() for each new point. Now, you could do a
preallocation strategy like lists do internally, but it's probably not worth it.

Robert Kern
robert.kern at gmail.com

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

More information about the Python-list mailing list