-1

I'm trying to make a 5x5 grid in which the player is placed in a random spot.

def board():
    grid0 = []
    grid1 = []
    a = 0
    b = 0
    while a < 5:
        grid0.append("0")
        a += 1
    while b < 5:
        grid1.append(grid0)
        b += 1
    x = list(grid1)
    x[0][0] = "x"
    for row in grid1:
        print(row)

I expect the outcome to look like this:

['X', '0', '0', '0', '0']
['0', '0', '0', '0', '0']
['0', '0', '0', '0', '0']
['0', '0', '0', '0', '0']
['0', '0', '0', '0', '0']

But instead I get this:

['x', '0', '0', '0', '0']
['x', '0', '0', '0', '0']
['x', '0', '0', '0', '0']
['x', '0', '0', '0', '0']
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
rei2001
  • 11
  • 3
  • Remove this line:x[0][0] = "x" – ncica Jun 26 '19 at 22:56
  • I'm assuming your expected output should have an X in the top left? It's effecting all the first elements because each row is the same list. You need to add new lists/make copies of the list before adding it or else all the rows will be effected at the same time. – Carcigenicate Jun 26 '19 at 22:57
  • Yeah I expect an X in the top left corner, I try to edit my question but it's not changing it – rei2001 Jun 26 '19 at 23:01
  • You need to make copies of the list before adding them to `grid0`. And the reason it wasn't showing up after the edit was you needed a newline after the backticks. – Carcigenicate Jun 26 '19 at 23:05

4 Answers4

0

If you want a 5x5 grid full of '0' with 'x' in a random position you can just do the following:

from random import randint


grid = [['0' for x in xrange(5)] for y in xrange(5)]
grid[randint(0,4)][randint(0,4)] = 'x'
jacalvo
  • 656
  • 5
  • 14
0

This is the classic python gotchya of multiple references the the same mutable list. You want to create unqiue lists:

from pprint import pprint

x = []
for _ in range(5):
    x.append(['0']*5)

x[0][0] = 'x'

pprint(x)

Gives the output:

[['x', '0', '0', '0', '0'],
 ['0', '0', '0', '0', '0'],
 ['0', '0', '0', '0', '0'],
 ['0', '0', '0', '0', '0'],
 ['0', '0', '0', '0', '0']]
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
0

The reason is the way you build the grid. Your list of lists 'x' is a list of 5 references to 'grid0'. When you overwrite the zeroeth element of the zeroeth element of the list 'x' by calling x[0][0] ='x', you are overriding the zeroeth element of the 'grid0' which represents each element of 'grid1' and therefore of your list 'x'. You will need to find another way to build your grid and look into how to gerate individual instances (e.g. by using copy() )

Err0neus
  • 26
  • 3
0

The problem with your code is that you're appending the same copy of grid0 to your grid1 list. This means that any change that you make to the grid0 in your grid1[0] will effect your grid0[1:4] (because they're all the same grid0).

You can easily fix this by appending a copy of grid0 to grid1 instead:

    while b < 5:
        grid1.append(grid0.copy())
        b += 1
Oreganop
  • 81
  • 1