preallocate list

beliavsky at aol.com beliavsky at aol.com
Wed Apr 13 12:44:20 EDT 2005


Jim wrote:
> Hi all
>
> Is this the best way to preallocate a list of integers?
> listName = range(0,length)

For serious numerical work you should use Numeric or Numarray, as
others suggested. When I do allocate lists the initial values 0:n-1 are
rarely what I want, so I use

ivec = n*[None]

so that if I use a list element before intializing it, for example

ivec[0] += 1

I get an error message

  File "xxnone.py", line 2, in ?
    ivec[0] += 1
TypeError: unsupported operand type(s) for +=: 'NoneType' and 'int'

This is in the same spirit as Python's (welcome) termination of a
program when one tries to use an uninitalized scalar variable.




More information about the Python-list mailing list