0

Why is arr[0] * 7 changing all element of arr to 7 and also arr[1][0] does not exist but the interpreter is result is 7. I am quite confused rn

    arr =[[]]*3
    arr[0].append(7)
    print(arr[0])   #[7]
    print(arr)      #[[7],[7],[7]]
    try:
       print(arr[1][0])  #7
    except IndexError:
       print("0")
GMuhammed
  • 85
  • 8
  • [What should I do when someone answers my question](https://stackoverflow.com/help/someone-answers) – RMPR Apr 28 '21 at 07:14

3 Answers3

1
arr = [[]] * 3

Creates an array of 3 references to the same list, so arr[1][0] is accessing the copy of the first list you initialized. What you probably want is:

arr = [[], [], []]

Or the more generic version:

arr = [[] for _ in range(N)]

That way when you do the appending you obtain the desired result:

arr[0].append(7) # [[7], [], []]

You can have a more detailed explanation reading my answer on Populate list of list with conditions

RMPR
  • 3,368
  • 4
  • 19
  • 31
  • 1
    You're correct, I just want to add that "link-safe" equivalent to `arr = [[]] * N` is `arr = [[] for _ in range(N)]`, there is no need to hardcode list of the list creation – NobbyNobbs Apr 28 '21 at 07:16
1

you have a two dimensional array but assign a value to the all references. you will see it if you

print(arr)

before and after every assignment

user3732793
  • 1,699
  • 4
  • 24
  • 53
1

Your first line does not actually create a matrix, it creates an array of three elements, where each element refers to the same object: an empty array. As such, arr[o].append(7) is exactly the same thing as arr[1].append(7) or arr[2].append(7).

If you want an easy way to visualize all that, try http://pythontutor.com/live.html#mode=edit

To easily create matrixes, use: matrix = [[0 for _ in range(y)] for _ in range(x)]