Have looked all over but can't seem to find info if not on numpy. Need to create a 3 x 6 zero matrix using python not numpy & for the output to look exactly like this:
Matrix 3 by 6 with 0's:
00 00 00 00 00 00
00 00 00 00 00 00
00 00 00 00 00 00
This works:
rows, cols = 3,6
my_matrix = [([0]*cols) for i in range(rows)]
Explanation:
([0]*cols) represents each element of the list built by the list expression (the outer square brackets in [([0]*cols) for i in range(rows)])([0]*cols) produces a one-dimensional list of zeros (as many zeros as the value of cols)So, effectively, the list expression builds a one-dimensional list of lists, where each inner list has cols zeros.
id(my_matrix[cur_row]) for all values of cur_row. You will see that the ids are all different.I assume you know how to make a list in python: my_list = [0, 0, 0]. To make a list of lists, we can just nest list definitions inside of another list: nested_list = [[0, 0, 0], [0, 0, 0]]. Obviously you won't want to write the whole thing out, so we can abstract this into a function:
def make_zeros(n_rows: int, n_columns: int):
matrix = []
for i in range(n_rows):
matrix.append([0] * n_columns)
return matrix
This makes an outer list and then appends inner lists ("rows") to it one at a time. That was meant to be a very clear definition regardless of your level with Python, but you can shorten this a bit if you want by using list comprehensions:
def make_zeros(n_rows: int, n_columns: int):
return [[0] * n_columns for _ in range(n_rows)]
Note that the inner lists are meant to be rows here, so you can easily access the rows:
matrix = make_zeros(3, 6)
matrix[0] # the first row
However, the "columns" consist of one element from each row; there isn't a list of these already, so if you wanted to get the first column, you have to do something like
col0 = [row[0] for row in matrix]
You could write a helper function to make this easier, but soon you'd be writing helper functions for all of the common matrix/array operations, and then you're reinventing the wheel that numpy has already made so nicely.
matrix, what exactly do you mean? Innumpy, that's defined. In Python, there is no "matrix" type. Do you want a list of lists? Or a tuple of tuples? Should the inner lists be rows or columns? Whichever one you pick, it will be easier to access those slices of the matrix than the others (e.g. easier to get a particular row than to get a column).[[str('00')] * 6] * 3if you need '00' or else :[[0] * 6] * 3[[0] * 6] * 3is what people are usually warned against doing, because, even though it builds an outer list of inner list references, all the inner list references refer to the same inner list object. So, if a modification is made to one row, it is effectively made to all rows.