I have created an empty 2D array. When I try to add stuff inside of it, it doesn't do so properly. Each index contains the appropriate info, but for some reason, carries the info from the previous into the next index. Here is my code:
rows, cols = (3, 2)
array = [[]*cols]*rows # Creating the empty 2D array.
fruit_list = ['apples', 'bananas', 'oranges'] # My fruit list
for i in range(0, 3):
array[i].append(fruit_list[i]) # Appending to the 2D array a fruit,
array[i].append(0) # followed by the number 0
print(array[i]) # Printing each index
The result I am getting in the console is :
['apples', 0] # This is good (index 1)
['apples', 0, 'bananas', 0] # This is not good (index 2)
['apples', 0, 'bananas', 0, 'oranges', 0] # This is not good (index 3)
# etc.
How do I stop this from happening? I want each index to have its own fruit and number 0.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…