For loop doesnt append info correctly into 2D array

2024/11/17 20:36:14

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 0print(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.

Answer

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']]
https://en.xdnf.cn/q/120163.html

Related Q&A

How to merge two strings in python?

I need to merge strings together to create one string. For example the strings for "hello" that need to be combined are: [H----], [-E---], [--LL-], and [----O]This is the current code I have …

ValueError: too many values to unpack (expected 3)?

I have been having issues with the code I am trying to right with the model I am trying to code the following error has appeared and being a relative novice I am unsure of how to resolve it.ValueError …

Finding a hello word in a different string, which it has hello in it

I should find a hello word in a string, which I gave it from input. Here is the code that I currently have, but I cannot match hello with the character list.mylist = it can be any letter plus hello in …

Building Permutation with Python

Im trying to write a programme to get all permutations of a string of letter using recursion. As Im a beginner in Python, I learnt about recursion with examples like Fibonacci Number and Factorial. I u…

Python: Is There a builtin that works similar but opposite to .index()?

Just a forewarning: I just recently started programming and Python is my first language and only language so far.Is there a builtin that works in the opposite way of .index()? Im looking for this beca…

Get a subset of a data frame into a matrix

I have this data frame:I want just the numbers under August - September to be placed into a matrix, how can I do this?I tried this cf = df.iloc[:,1:12] which gives me but it gives me the headers as w…

Get Pairs of List Python [duplicate]

This question already has answers here:How can I iterate over overlapping (current, next) pairs of values from a list?(13 answers)Closed 9 years ago.c = [1,2,3,4,5,6,7,8,9,10]for a,b in func(c):doSome…

Python - make a list

How can I turn something like this: (not a file)Edit: Its what I get when I print this:adjusted_coordinate_list = str(adjusted_X_coordinate) + , + str(Y_coordinate)1,1 1,2 1,3 1,4 1,5into this:[1,1,1,2…

Error while running test case

I need to test my code below. I am using one test to see if it is working or not. but dont know what exactly I should pass as a parameter in the test code. Please see the test code at the end and pleas…

How to run something on each line of txt file?

I am trying to get this to run on each line of a .txt file.D1 =int(lines[0])*10 D2 =int(lines[1])*9 D3 =int(lines[2])*8 D4 =int(lines[3])*7 D5 =int(lines[4])*6 D6 =int(lines[5])*5 D7 =int(lines[6])*4 D…