0

I am trying to create a matrix using python and I found a very interesting result. The matrix that I have created by using bad_list = [[0] * 4] * 4. But then when I want to change only bad_list[0][0] = 1 the output for bad list will [[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]. This is not what I want so I use a second approach by

        for i in range(4):
            insertlist = [0] * 4
            dynamic_list.append(insertlist)

Then When I use dynamic_list st[0][0] = 1 the reuslt will be [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] , which is what I expected to perform. I thought there might be something wrong will my first matrix so I compare dynamic_list with bad_list, but they return True, which mean they are the same structure. But why I performed a same operation on same data structure and gives me different output?

        s = "1234"
        bad_list = [[0] * len(s)] * len(s)
        print(bad_list)

        dynamic_list = []

        for i in range(len(s)):
            insertlist = [0] * len(s)
            dynamic_list.append(insertlist)
        print(dynamic_list)
        
        if(bad_list == dynamic_list):
            print("true")
        else:
            print("false")


        bad_list[0][0] = 1
        dynamic_list[0][0] = 1 
        
        if(bad_list == dynamic_list):
            print("true")
        else:
            print("false")

0 Answers0