0

i want to make a code that takes in the x and y coordinates as inputs and a 2d list as an output to match the x and y coordinates.

This is my code:

def d2_coordinate(size,x,y):
    d2_plane = []
    d2_row = []
    for i in range(size * 2 + 1):
        d2_row.append(0)
    for i in range(size * 2 + 1):
        d2_plane.append(d2_row)
    d2_plane[size - y][size + x] = 1
    return d2_plane

size = int(input(""))
x_coordinate = int(input(""))
y_coordinate = int(input(""))

print(d2_coordinate(size,x_coordinate,y_coordinate))

so lets say i put in numbers like size = 2, x = 0, y = 0, i expect the outcome of

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

instead, i get

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

i dont understand what i did wrong here. Please help me out!

  • 2
    you are not copying a list, you are inserting the same reference to the same data into your list, then change the data - all references reference the same data so you get what you have. Use `d2_plane.append(d2_row[:])` to insert copyies for your row instead (shallow copy) - read the dupe for more explanation. – Patrick Artner Jul 28 '18 at 15:05
  • You can also use `id()` to identify if your refererences are distinct or same: `print(list(map(id,d2_plane)))` will print all ids of the rows that you added to d2_plane - if they are identical they reference the same data. this is a common mistake for ealier python users - you can research more about it if you read about differences between `immutables` (tuples, strings, ..) and mutables (list,set,dict,...) – Patrick Artner Jul 28 '18 at 15:11
  • thanks so much, didnt expect such a quick answer! – Dongwook Chang Jul 28 '18 at 15:13
  • Rember it, SO is fast, especially for "easy" questions. Best to stick around the site for ~15 to 30min after asking a question, else the wannabe answerers do not get theire questions in comment answered, get cranky and downvote due to "non-responsiveness" ;) we are working on our social skills here, but downvotes/closevotes do not mean you did bad, sometimes its just thats this question comes up about 3-10 times a week ;o) and got good canonical answeres - hence the "dupe" link to read up upon. – Patrick Artner Jul 28 '18 at 15:18

0 Answers0