Home > Software design >  Am I doing something wrong when writing values to nesting lists?
Am I doing something wrong when writing values to nesting lists?

Time:12-13

I am writing code using nesting lists as a grid system and am having trouble with something. Here is the code I'm using:

N = int(input(""))
Yard = \[\]
Yardhelper = \[\]

for n in range(0,N):
Yardhelper.append("")
for n in range(0,N):
Yard.append(Yardhelper)

for n in range(0,int(input(""))):
treepos = \[int(x) for x in input().split(" ")\]
Yard\[treepos\[0\]\] \[treepos\[1\]\] = 1
print(Yard)

the input format is

line 1: size of yard
line 2: number of trees
line 3 : coordinates for trees (input should be 'x y' (no quotes)

Try it yourself, I can't figure it out.

I poked around and found I can access the lists and read their values fine it's just writing in values. Let's say I give the input 3, then on the next line I want one tree so I put 1, then the next I put the coordinates: 0 1. It should give the result

[[0, 1, 0], [0, 0, 0], [0, 0, 0]]

but instead, it prints

[[0, 1, 0], [0, 1, 0], [0, 1, 0]]

I don't know why this happens and neither do any of my friends, who are a bit better at coding than me. They all say my code looks good and are puzzled

CodePudding user response:

The problem with your code is that you are putting reference of list 'Yardhelper' into list 'Yard' in your second for loop.

What you are tring to do is to make same sized list inside of another list but the way you are doing it adds reference in list 'Yard' to list 'Yardhelper' instead of adding values.

Simple way to fix this is to not use another list to make multidimensional list as lists aren't pass by value but pass by reference, in other words you don't make copies of list 'Yardhelper' when you append it in your second for loop but you give address of list 'Yardhelper' on all indexes of list 'Yard'. All of the elements of list 'Yard' are one and the same, if you change any of the elements of list 'Yardhelper' all other elements of list 'Yard' also change.

This behaviour is useful when you want to pass your list to some function, so that function could change values of this list but in your case you just end up referencing same element on different indexes.

here is code how to make a 2d list without it referencing other list

N = int(input(""))
Yard = []

for n in range(N):
    Yard.append(["" for x in range(N)]) #this fills in list of size N with characters ""

for n in range(0,int(input(""))):
    treepos = [int(x) for x in input().split(" ")]
    Yard[treepos[0]] [treepos[1]] = 1

print(Yard)

this code with inputs

5

3

1 0

0 1

2 3

results in

[['', 1, '', '', ''], [1, '', '', '', ''], ['', '', '', 1, ''], ['', '', '', '', ''], ['', '', '', '', '']]

  • Related