0

i am fairly new to python, and this is the first hurdle i came across. Here is what's happening:

from random import randint

empty = [[0]*9]*9

def randomboard():
  board = empty
  for x in range(0,8):
    for y in range(0,8):
      nextInt = randint(0,29) - 20
      #nextInt = 0 if nextInt < 0 else nextInt
      board[x][y] = nextInt
  return board

def printboard(board):
  for x in range(0,8):
    print(board[x])
  print("----")

printboard(empty)
printboard(randomboard())

The Output is the following:

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

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

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

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

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

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

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

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


[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]


What the Code should do: Create an Empty 9x9 board. Fill it with random values. Then print the result.

As you can see, the first axis keeps repeating, even though i feel like this should not be the case and i can only try to fathom why it is. Here are a couple of possibilities:

-The RNG Seed resets after every iteration of the first loop: I wouldn't even know what to do in this case, and it would seem very unintuitive for this to happen.

-I have been doing something weird during the construction of the random list.Possibly some false syntax, that i have been taking over from java: I have been looking into other code examples, and the code snippet still seems good to me. Maybe i'm not seeing something, that you do.

-The printboard function just prints the first row over and over: I already tried to substitute the funtion for "print(board)", but that also returns the repeating list.

-Something totally different, that i have been overlooking

At this point, i'd really appreciate your help.

Thank you in advance!

Community
  • 1
  • 1
  • Incredible, yes it does! Altough, I accidentaly clicked on "no", i'm sorry. I will have to look into this a bit more, now that i have a entry-point. Thank you! – NougatNode Feb 14 '20 at 13:13

1 Answers1

0

I think you are doing a list of references to the same object. Have a look at this post: Python initializing a list of lists.

My solution for your problem would look like a little different. I would not start with an empty list, just add what I need:

def randomboard():
    board = []
    for x in range(0,8):
        newline = []
            for y in range(0,8):
                newline.append(randint(0,29) - 20)
        board.append(newline)
    return board
vaeng
  • 90
  • 15