Shashwat Pandey
Shashwat Pandey

Reputation: 11

Why iterating and modifying the each element in nested list results in some wrong output?

The immutable and mutable is causing problem.

I was trying to rotate the matrix by 90 degree clockwise without changing the argument passed in function.

def rotate(m):
    rm=[[0]*len(m)]*(len(m))
    print("m:",m)
    print("rm:",rm)
    for j in range(len(rm)):
        for i in range(len(rm)):
            k=m[j][i]
            y=(len(rm)-j-1)
            rm[i][y] = k
            print(i," ",len(rm)-j-1," ",rm[i][(len(rm)-j-1)])
    print("m:",m)
    print("rm:",rm)
    return rm

 print(rotate([[1,2,3],[4,5,6],[7,8,9]]))

I expect the rm should be "[[7, 4, 1], [8, 5, 2], [9, 6, 3]]" but it is "[[9, 6, 3], [9, 6, 3], [9, 6, 3]]" at the end of function.

Upvotes: 1

Views: 25

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195438

You are seeing the error, because the line rm=[[0]*len(m)]*(len(m)). Try to change it for:

rm = [[0 for _ in range(len(m))] for _ in range(len(m))]

Note: The above function can be rewritten as:

l = [[1,2,3],[4,5,6],[7,8,9]]

def rotate(lst):
    return [list(val[::-1]) for val in zip(*lst)]

print(rotate(l))

This prints:

[[7, 4, 1], [8, 5, 2], [9, 6, 3]]

Upvotes: 2

Related Questions