Reputation: 191
I am trying to compute a transpose of the matrix, which I have in the form of list of lists. The initial matrix is mn, I have created a matrix nm. The problem appears when I start to use the nested loop.
m = 0
for i in range(0, rows):
for j in range(0, columns):
final1[j][i] = m
print(final1)
m += 1
I deliberately print the whole list of lists (final) to see how at each step my values are changing, also I just assign consequent natural numbers for simplicity. what I see is (first 4 lines of the output)
[[0, None, None, None], [0, None, None, None], [0, None, None, None]]
[[1, None, None, None], [1, None, None, None], [1, None, None, None]]
[[2, None, None, None], [2, None, None, None], [2, None, None, None]]
[[2, 3, None, None], [2, 3, None, None], [2, 3, None, None]]
So, by accessing final[j][i], at position j = 0, i = 0 the values final[1][0] and final[2][0] are also changing. How to avoid this? and make the first 4 lines of this format:
[[0, None, None, None], [None, None, None, None], [None, None, None, None]]
[[0, None, None, None], [1, None, None, None], [None, None, None, None]]
[[0, None, None, None], [1, None, None, None], [2, None, None, None]]
[[0, 3, None, None], [1, None, None, None], [2, None, None, None]]
rows = int(input())
columns = int(input())
final1 = [[None] * rows] * columns
This is the way I declare final1
Upvotes: 0
Views: 62
Reputation: 463
This happens because the declaration statement is internally equivalent to appending a single list ([None]*rows)
column
times into the final1
list.
If you are familiar with copy problem , this is nearly the same. All the lists inside final1
are the same lists in terms of the memory they represent.
That's why when you update a value in one list, it gets reflected to all.
Note : You are actually creating a list of lists with column
number of rows and row
number of columns.
You can solve this issue by declaring final1 this way :
final1 = [[None for i in range(rows)] for j in range(columns)]
p.s: I've used rows inside and columns outside just to make it as an alternative to your declaration. It still produces a list of lists with column
number of rows and row
number of columns
Upvotes: 2
Reputation: 1812
This works:
rows = int(input())
columns = int(input())
final1 = [[None for i in range(rows)] for j in range(columns)]
m = 0
for i in range(rows):
for j in range(columns):
final1[j][i] = m
m += 1
print(final1)
Upvotes: 1