More elegant way to create a 2D matrix in Python
Solution 1
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)
Solution 2
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)
Solution 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))
Solution 4
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.
user1068051
Updated on February 10, 2020Comments
-
user1068051 over 4 years
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?