0

I am new to Python. Can somebody explain please why is this code not populating the 2D array as Pascal's triangle?

def PascalTri(n):
    ar=[[0]*n]*n
    print(ar)
    for i in range(0,n):
        for j in range(0,i+1):
            if j==0 or i==j:
                ar[i][j]=1
            else:
                ar[i][j]=ar[i-1][j-1] + ar[i-1][j]

    print(ar)

PascalTri(5)

Output :

[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[[1, 4, 8, 9, 1], [1, 4, 8, 9, 1], [1, 4, 8, 9, 1], [1, 4, 8, 9, 1], [1, 4, 8, 9, 1]]
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • 2
    tl;dr `ar = [[0] * n for _ in range(n)]` – Aplet123 Dec 26 '20 at 20:51
  • 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) – ssp Dec 26 '20 at 20:51
  • `ar=[[0]*n]*n` doesn't work the way you think it does. – Code-Apprentice Dec 26 '20 at 20:53
  • Thanks Sir. I think I got the idea. I thought it will create a 2D array and initialize it with zeros. But that isn't the case. I will read more regarding it. @Code-Apprentice – user6386269 Dec 26 '20 at 21:03

0 Answers0