i have a matrix
Matrix = [[[]] * 5 for i in range(5)]
i'm trying to change the inner element with the following code, but somewhy it changes the whole row instead:
Matrix[0][1].append(1)
output:
[[[1], [1], [1], [1], [1]], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []]]
but i wanted it to work like this:
[[[], [1], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []]]
CodePudding user response:
You want to use loops inside and outside the list of lists to avoid creating copies.
Matrix = [[[] for _ in range(5)] for i in range(5)]
print(Matrix)
[[[], [1], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []]]