Detailed explanation of the example of multiplying a list by a certain number in Python3
- 2021-07-24 11:19:46
- OfStack
In the Python list operation, the list is multiplied by a certain number, such as list2 = list1 * 2 to get a new list. The elements of list1 are repeated n times, and list1 does not change.
But when you run the following code, you get the new list b, where b [0] and b [1] have the same address, that is, if you operate on b [0], b [1] will also change.
a = [0]
b = [a] * 2
print(b)
b[0].append(1)
print(b)
The output is:
[[0], [0]]
[[0, 1], [0, 1]]
Then try the following code:
Code (1)
a = [0]
b = [a for _ in range(2)]
print(b)
b[0].append(1)
print(b)
The output is still:
[[0], [0]]
[[0, 1], [0, 1]]
Code (2)
a = [0]
b = [list(a) for _ in range(2)]
print(b)
b[0].append(1)
print(b)
The output is:
[[0], [0]]
[[0, 1], [0]]
Code (3)
b = [[] for _ in range(2)]
print(b)
b[0].append(1)
print(b)
The output is:
[[], []]
[[1], []]