0
transposta = []
nova_linha = []
for i in range (len(matriz)):
    for j in range(len(matriz[i])):
        nova_linha.append(matriz[i][j])
        i+=1
    transposta.append(nova_linha)
    j+=1
    nova_linha = []
return transposta

I am getting the list index out of range error in line nova_linha.append(matriz[i][j])

why is this happening?

G.C.
  • 13
  • 1
  • 1
    Please post the entire exception, not a loose description of it. – abarnert May 05 '18 at 00:26
  • Plus code that reproduces the exception. – Aran-Fey May 05 '18 at 00:29
  • 1
    This entire thing seems to be an attempt to transpose a square matrix (stored as a list of lists), which [you can write as a one-liner with `zip`](https://stackoverflow.com/questions/19339/transpose-unzip-function-inverse-of-zip). But of course it's worth learning how to write it explicitly, too (and how to use `for` loops). – abarnert May 05 '18 at 00:30

1 Answers1

4

This would work fine:

for i in range (len(matriz)):
    for j in range(len(matriz[i])):
        nova_linha.append(matriz[i][j])    
    transposta.append(nova_linha)
    nova_linha = []

However, you added in lines that do i += 1 and j += 1. A for loop over a range already takes care of that for you.

Normally, that would be as harmless as it is useless, because your change would just get thrown away the next time through the loop—but you also got them backward. So now, each time through the inner loop, you increment i, and pretty quickly you run off the bottom of the matrix.

abarnert
  • 354,177
  • 51
  • 601
  • 671