16

Possible Duplicate:
How to initialize a two-dimensional array in Python?

I have always written this part of code in this way: every time I need it, I use this python code:

for x in range(8):
        a.append([])
        for y in range(8):
            a[x].append(0)

However, I'd like to know if there's a way to beautify this piece of code. I mean, how do you create a bidimensional matrix in python, and fill it with 0?

Community
  • 1
  • 1
user1068051
  • 217
  • 1
  • 4
  • 12
  • this problem is of declaring and initializing two dimensional array is explained nicely [here](http://stackoverflow.com/questions/2397141/how-to-initialize-a-two-dimensional-array-in-python) – gaurav Dec 10 '11 at 17:22

4 Answers4

20

Use nested list comprehensions:

a = [[0 for y in range(8)] for x in range(8)]

which is eqivalent to

a = []
for x in range(8):
    row = []
    for y in range(8):
        row.append(0)
    a.append(row)
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
3

List comprehension is more concise.

a = [[0 for i in xrange(8)] for i in xrange(8)]
print a

Or you can use numpy arrays if you will do numerical calculations with the array. Numpy.zeros function creates a multi dimensional array of zeros.

import numpy as np

a = np.zeros((8,8))
Bora Caglayan
  • 151
  • 1
  • 7
3

Try this:

a = [[0]*8 for _ in xrange(8)]

It uses list comprehensions and the fact that the * operator can be applied to lists for filling them with n copies of a given element.

Or even better, write a generic function for returning matrices of a given size:

# m: number of rows, n: number of columns
def create_matrix(m, n):
    return [[0]*n for _ in xrange(m)]

a = create_matrix(8, 8)
Óscar López
  • 232,561
  • 37
  • 312
  • 386
2

You can use list comprehensions. Since you don't really care about the values provided by range, you can use _, which is conventionally stands for a value, which one isn't interested in.

>>> z = [[0 for _ in range(8)] for _ in range(8)]
>>> import pprint
>>> pprint.pprint(z)
[[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]]

List comprehensions provide a concise way to create lists without resorting to use of map(), filter() and/or lambda. The resulting list definition tends often to be clearer than lists built using those constructs.

miku
  • 181,842
  • 47
  • 306
  • 310