Python - as a shallow copy of a list object multiplication

Run the following code

 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)

You will get wonderful results

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]]

Key output on line 5, line 13 to reflect the modification of the program.

As can be seen the object list multiplication shallow copy, pay special attention in use.

Guess you like

Origin www.cnblogs.com/adjwang/p/11809696.html