The Python Oracle

How can I design a Python function to print a matrix with only the forward diagonal elements set to True?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle

--

Chapters
00:00 How Can I Design A Python Function To Print A Matrix With Only The Forward Diagonal Elements Set To
00:42 Answer 1 Score 1
00:53 Accepted Answer Score 1
01:08 Thank you

--

Full question
https://stackoverflow.com/questions/6886...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #arrays #multidimensionalarray

#avk47



ANSWER 1

Score 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])



ACCEPTED ANSWER

Score 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)