I have a problem where I want to have a nested for loop concatenate a string. For some reason I’m not getting the correct output. Can someone give me some advice? This should be simple.
newRow = []
matrix = []
for i in range(0,3):
for j in range(0,5):
newRow.append(j)
matrix.append(newRow)
print matrix
python test.py
[[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4],
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4],
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]]
I want it to print…
[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]
You keep adding to the same
newRow. If you want to get a clean row, you need to create an empty one on each iteration:There are, of course, more pythonic ways of achieving this, but I’m trying to point out what the problem with the code is.