Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preallocate a list of lists?

Tags:

python

I am creating a list of lists using this code:

zeroArray = [0]*Np
zeroMatrix = []
for i in range(Np):
    zeroMatrix.append(zeroArray[:])

Is there a more efficient way to do this? I'm hoping for something along the lines of zeroArray = [0]*Np; zeroMat = zeroArray*Np but can't find anything similar.

like image 819
Charles L. Avatar asked Mar 18 '11 01:03

Charles L.


1 Answers

Perhaps this is what you'd like?

zeroMatrix = [[0 for _ in range(Np)] for _ in range(Np)]

I'm not sure if this will provide a performance benefit (profile, as always) but I don't really know what you mean by "efficient." Other than avoiding the use of list.append.

like image 108
Chris Lutz Avatar answered Oct 10 '22 20:10

Chris Lutz