You are manipulating the same list over and over again, not a copy.
Create a new list in the loop instead:
for elemento in lista_base:
listado = [elemento, elemento + 1, elemento + 2]
tabla.append(listado)
or create a copy of the list:
for elemento in lista_base:
listado[0] = elemento
listado[1] = elemento+1
listado[2] = elemento+2
tabla.append(listado[:])
where [:]
returns a full slice of all the elements. You could also use list(listado)
or import the copy
module and use copy.copy(listado)
to create a copy of the existing list.
Appending a list to another list only adds a reference, and your code thus created many references to the same list that you kept changing in the loop.
You could have seen what was happening had you printed tabla on every loop. Printing listado
on every loop iteration only shows that the state of that list was correct for that iteration, not that all the references to that list in tabla
were changing along with it:
>>> tabla = []
>>> listado = [0, 0, 0]
>>> for elemento in range(3):
... listado[0] = elemento
... listado[1] = elemento+1
... listado[2] = elemento+2
... tabla.append(listado)
... print 'tabla after iteration {}: {!r}'.format(elemento, tabla)
...
tabla after iteration 0: [[0, 1, 2]]
tabla after iteration 1: [[1, 2, 3], [1, 2, 3]]
tabla after iteration 2: [[2, 3, 4], [2, 3, 4], [2, 3, 4]]
Notice how all tabla
lists change together; they are in fact all the same list. If you create a new list instead, things work as expected:
>>> tabla = []
>>> for elemento in range(3):
... listado = [elemento, elemento + 1, elemento + 2]
... tabla.append(listado)
... print 'tabla after iteration {}: {!r}'.format(elemento, tabla)
...
tabla after iteration 0: [[0, 1, 2]]
tabla after iteration 1: [[0, 1, 2], [1, 2, 3]]
tabla after iteration 2: [[0, 1, 2], [1, 2, 3], [2, 3, 4]]