I have a question about the Python list product operation.

Asked 2 years ago, Updated 2 years ago, 15 views

import numpy as np

table = [[0]*5]*5
table[0][0] = -1
print(table[0][0])
print(np.reshape(table, (5, 5)))

table2 = [[0,0,0,0,0]*5]
table2[0][0] = -1
print(table2[0][0])
print(np.reshape(table2, (5, 5)))    
#table 
-1
[[-1  0  0  0  0]
    [-1  0  0  0  0]
    [-1  0  0  0  0]
    [-1  0  0  0  0]    
    [-1  0  0  0  0]]
#table2
-1
[[-1  0  0  0  0]
    [ 0  0  0  0  0]
    [ 0  0  0  0  0]
    [ 0  0  0  0  0]
    [ 0  0  0  0  0]]

What's the reason for the results?

python

2022-09-20 19:39

1 Answers


table = [[0]*5]*5
table[0][0] = -1
print(table)        
print(table[0][0])
print(id(table[0]), id(table[2]), id(table[3]))

######################
# [[-1, 0, 0, 0, 0], [-1, 0, 0, 0, 0], [-1, 0, 0, 0, 0], [-1, 0, 0, 0, 0], [-1, 0, 0, 0, 0]]
# -1
# 2106814512832 2106814512832 2106814512832

The last result shows that table[0] table[1] table[2] is not a different list, but the same list (not just the same value).

It's a bit confusing when I first did Python. You should also be careful about transferring list factors as a function.


2022-09-20 19:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.