运行下面这段代码
1 # !/usr/bin/env python3 2 # -*- coding=utf-8 -*- 3 4 temp_a = [[0]*2]*3 5 temp_b = [[0]*2 for i in range(3)] 6 7 print(temp_a) 8 print(temp_b) 9 10 print(id(temp_a[0]) == id(temp_a[1])) 11 print(id(temp_b[0]) == id(temp_b[1])) 12 13 temp_a[0][0] = 1 14 temp_b[0][0] = 1 15 16 print(temp_a) 17 print(temp_b)
会得到奇妙的结果
1 [[0, 0], [0, 0], [0, 0]] 2 [[0, 0], [0, 0], [0, 0]] 3 True 4 False 5 [[1, 0], [1, 0], [1, 0]] 6 [[1, 0], [0, 0], [0, 0]]
重点在输出的第5行,反映了程序第13行的修改。
可以看出list对象的乘法操作是浅拷贝,在使用时要特别注意。