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?
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With