Issue
So basically, I want to convert the input into a 2d array. The input is 5 x 5. I did what I think is logical but it still prints out the incorrect arrays. Somehow whenever I change arr[0][0] to something, arr[1][0], arr[2][0], arr[3][0],.... changes along with it. I'm not sure what I did wrong here.
This is the code I tried(sry if the variables are confusing):
side = 5
L = []
a = []
arr=[[0]*side]*side
for o in range(5):
i = input()
a.append(i)
d = 0
for i in a:
c = 0
for b in i:
L.append(b)
arr[d][c] = L.pop(0)
c += 1
d += 1
print(arr)
Solution
You initialized the array the wrong way. the way you do it it creates a list with references to the same list hence the cascading changes. Its as if you had five copies of the same list for each row. Consequence being that modifying one row affects all other rows elements in the same column. Thats why changing arr[0][0] affects arr[1][0] for example.
Solution for that is assigning an own list for each row. That would look like this:
arr = [[0] * side for _ in range(side)]
the "for _ in range(side)" creates the inner list within the array for each row.The "_" is a common variable name in python used when the value of that variable is not used later on. In this example its just something like "do it range(side) times"
Hope this helped! :)
*Edit Further Explanation: List of lists changes reflected across sublists unexpectedly
Answered By - Dario Colcuc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.