-2

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.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • This seems good! What else would you expect to have ? please show your expected output so we know what you want to do. – Malo Mar 20 '21 at 21:58
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Manuel Mar 20 '21 at 22:19

1 Answers1

2

The issue is with this:

array = [[]*cols]*rows

First, []*cols is just creating one empty list (empty, because the * operator has nothing to repeat). But more importantly, *row just duplicates the reference to that list, but does not create new empty lists. So whatever you do to that single list, will be visible in all the slots of the outer list.

So change:

array = [[]*cols]*rows 

To a list comprehension:

array = [[] for _ in range(rows)]

Improvement

Not your question, but you can omit the loop and use the above mentioned list comprehension to immediately populate the list with the data:

array = [[fruit, 0] for fruit in ['apples', 'bananas', 'oranges']]
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Another approach would be using `array.append([fruit_list[i],0])` then you could just initialise the array with `array=[]` – JeffUK Mar 20 '21 at 22:07