Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - multi-line array

Tags:

python

arrays

in c++ I can wrote:

int someArray[8][8];
for (int i=0; i < 7; i++)
   for (int j=0; j < 7; j++)
      someArray[i][j] = 0;

And how can I initialize multi-line arrays in python? I tried:

array = [[],[]]
for i in xrange(8):
   for j in xrange(8):
        array[i][j] = 0
like image 250
Max Frai Avatar asked Apr 13 '10 14:04

Max Frai


4 Answers

>>> [[0]*8 for x in xrange(8)]
[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
>>>
like image 113
YOU Avatar answered Oct 14 '22 05:10

YOU


You asked about initializing a list of lists. Its a very useful data structure, but it has an important difference from the 2D array in C++: There are no guarantees that all lines have the same length (i.e, that len(a[0])==len(a[1]) (while in C++ you do have that guarantee).

So another solution that might be handy, is using NumPy's array datatype, like this:

import numpy as np
array = np.zeros((8,8))
like image 25
Ofri Raviv Avatar answered Oct 14 '22 04:10

Ofri Raviv


Here is a shorter way:

array = []
for i in xrange(8):
    array.append( [0] * 8 )
like image 43
Justin Ethier Avatar answered Oct 14 '22 05:10

Justin Ethier


array = [[0]*8 for i in xrange(8)]
like image 34
Phong Avatar answered Oct 14 '22 04:10

Phong