Array generator in Python

0
The program does the following: I say the number of rows and columns I want in my array and then assign a value to each column in each row, the problem is that it seems that when I specify the number of rows through the append () it creates a "false list", putting the elements of the first sublist in all others:

lista = []
linha = []
nc = int(input('Quantas colunas? '))
nl = int(input('Quantas linhas? '))
for c in range(0, nl):
    lista.append(linha)
for c1 in range(0, nl):
    for c2 in range(0, nc):
        n = int(input(f'Número L[{c1+1}] C[{c2+1}]: '))
        lista[c1].append(n)
print(lista)

And if I try to put lista[c1][c2] it gives the following error:

'lista[c1][c2].append(n)'
> zIndexError: list index out of range'

Output:
Quantas colunas? 3
Quantas linhas? 3 
Número L[1] C[1]: 1
Número L[1] C[2]: 2 
Número L[1] C[3]: 3
Número L[2] C[1]: 4 
Número L[2] C[2]: 5
Número L[2] C[3]: 6 
Número L[3] C[1]: 7 
Número L[3] C[2]: 8 
Número L[3] C[3]: 9 
[[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9]]

'

Now when I leave the number of rows defined

lista = [[], [], []]
for c1 in range(0, 3):
    for c2 in range(0, 3):
        n = int(input(f'Número L[{c1+1}] C[{c2+1}]: '))
        lista[c1].append(n)
print(lista)

It adds the numbers to the correct positions:

Número L[1] C[1]: 1
Número L[1] C[2]: 2
Número L[1] C[3]: 3
Número L[2] C[1]: 4
Número L[2] C[2]: 5
Número L[2] C[3]: 6
Número L[3] C[1]: 7
Número L[3] C[2]: 8
Número L[3] C[3]: 9
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Thank you very much if you can help me!

    
asked by anonymous 09.02.2018 / 02:33

2 answers

2

The problem is that in your loop you create a list and assign it the variable line - and then you assign that same list to each position in your array.

If you create a new list on each line, it will work:

lista = []
nc = int(input('Quantas colunas? '))
nl = int(input('Quantas linhas? '))
for c in range(0, nl):
    lista.append([])
...

So, with each interaction of c , a new list is created (when Python finds the expression [] - could also be a call to list() : it does the same).

    
09.02.2018 / 14:39
0

The array is being created the wrong way it should be created like this:

lista = []
linha = []
nc = int(input('Quantas colunas? '))
nl = int(input('Quantas linhas? '))
for c1 in range(0, nl):
    linha = []
    for c2 in range(0, nc):
        n = int(input('Número L[{0}] C[{1}]: '.format(c1 + 1,c2 + 1)))
        linha.append(n)
    lista.append(linha)
print(lista)
  

But why?

     

Because so the columns (the number of each) already go straight to their lines preventing any kind of error.

    
11.02.2018 / 02:44