I have a doubt with the creation of arrays in Python, specifically with the following code:
def inicializaMatriz(FILAS,COLUMNAS):
matrizA = []
for i in range(FILAS):
a = [0]*COLUMNAS
matrizA.append(a)
return matrizA
This is an implementation I found, but what is not very clear to me is the line:
a = [0]*COLUMNAS
I have an idea about what it does but does anyone know how to interpret that line?
In answer to your question, the specific code you ask for creates a list of zeros with the length of
COLUMNAS
.Now a recommendation, if you are going to work with arrays in Python, it is best to use a specialized library such as
numpy
.You can use numpy.zeros :
We can create arrays full of zeros or with data.
First we import the library
numpy
np.zeros((3,3), int)
will create a 3-row, 3-column all-zero int array.np.matrix([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
will create an array of type int with the values assigned in the lists.What does the code provided in the initial question do?
This code generates lists of lists based on the row and column values entered by parameters.
If we call the function
inicializaMatriz(FILAS,COLUMNAS)
of the initial question with the values of rows and columns we will obtain the following:The variable
a
is a list of zeros created with the value entered as a parameter for the columns.For 4 columns the variable
a
is added to the list with the sublist.I hope you find it useful.