0

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], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []]]
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – j1-lee May 25 '22 at 18:30
  • shouldn't be : Matrix[0][1] = [1] – Marya May 25 '22 at 18:34
  • @j1-lee it looks like im already using a solution from there – schoolboychik May 25 '22 at 18:38
  • @Marya yeah that works, but im curious why cant i use append – schoolboychik May 25 '22 at 18:38
  • 1
    @schoolboychik No you're not. You still have `[[]] * 5`. Try `Matrix = [[[] for _ in range(5)] for _ in range(5)]`. Then you are good to use `append`. – j1-lee May 25 '22 at 18:40
  • append add the value to your matrix. You want to change the value. That's why you should not use the append. – Marya May 25 '22 at 18:41

1 Answers1

1

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], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []]]

AboAmmar
  • 5,439
  • 2
  • 13
  • 24