Question about Python syntax


  • 0
    D
    def generateMatrix(self, n):
        ans = []
        for x in xrange(n):
            ans.append([0]*n)
        mini, minj, maxi, maxj = 0, 0, n-1, n-1
        num = 1
        
        while maxi >= mini and maxj >= minj:
            #right
            for j in xrange(minj, maxj+1):
                ans[mini][j] = num
                num += 1
            mini += 1
    
            #down
            for i in xrange(mini, maxi+1):
                ans[i][maxj] = num
                num += 1
            maxj -= 1
    
            #left
            for j in xrange(maxj, minj-1, -1):
                ans[maxi][j] = num
                num += 1
            maxi -= 1
    
            #up
            for i in xrange(maxi, mini-1, -1):
                ans[i][minj] = num
                num += 1
            minj += 1
        return ans
    

    Here is my solution. It's a pretty mundane. My question is that originally instead of

    ans = []
    for x in xrange(n):
        ans.append([0]*n)
    

    I just had

    ans = [[0]*n]*n
    

    However, with this second syntax, whenever I changed an element in one row of the matrix, it changed it in every row. That is, setting x[0][0] = 1 also set x[1][0] = 1 and x[2][0] = 1, etc. Why does it do that? Is there a pythonic way of writing this snippet without the for loop?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.