Why is this happeneing? Is this a bug or am I doing something wrong?


  • 0
    A
    ans=[[0]*n]*m
           
    print ans
    ans[2][0]=1
    print ans
    

    output->

    [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

  • 0

    Well you're using three times the same list object. The output is exactly what's expected from that code. If you want three independent list objects, then do that. Usually that's done with [[0]*n for _ in range(m)].


  • 0
    A

    Thank you! I am new to python so I keep facing these kind of issues!


Log in to reply
 

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