3

I'm trying to print an n*n matrix with only the forward diagonal elements set to True and the rest to False.

Here is my code:

def func(n):
    dp = [[False]*n]*n
    for i in range(n):
        dp[i][i] = True
    print(dp)

I'm baffled as to why the True values are spreading through the entire matrix instead of remaining confined to the cells where i=j.

Desired output for n=5:

True False False False False
False True False False False
False False True False False
False False False True False
False False False False True

Current output for n=5:

True True True True True
True True True True True
True True True True True
True True True True True
True True True True True

What could be the issue here?

Shield77
  • 149
  • 2
  • 8

2 Answers2

1

The problem is that the shorthand you're using to create lists actually just creates copies of the same list. You can check this with the id function:

n = 5
dp = [[False]*n]*n
print([id(x) for x in dp])
Toby Petty
  • 4,431
  • 1
  • 17
  • 29
1

The reason is that multiplying with * does not create new object, as @TobyPetty mentioned.

The way to fix would be:

def func(n):
    dp = [[[False] for i in range(n)] for x in range(n)]
    for i in range(n):
        dp[i][i] = True
    print(dp)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114