Search code examples
pythongrid

How do I make a grid in python?


This is my code

width = int(input("How wide?"))
height = int(input("How high?"))
grid = []
row = []
bak = "."
for i in range(width):
    row.append(bak)
for i in range(height):
    grid.append(row)
while True:
    for i in range(len(grid)):
        print(grid[i])

It's not working and i don't know why. This is what i get when i put 5 width and 5 height:

['.', '.', '.', '.', '.']
['.', '.', '.', '.', '.']
['.', '.', '.', '.', '.']
['.', '.', '.', '.', '.']
['.', '.', '.', '.', '.']

That's fine and all but when i change the bottom left dot by using this: grid[0][0] = "a". This happens:

['a', '.', '.', '.', '.']
['a', '.', '.', '.', '.']
['a', '.', '.', '.', '.']
['a', '.', '.', '.', '.']
['a', '.', '.', '.', '.']

It thinks the "row" list is a tag, when it is clearly coded not to be. How to fix this problem?


Solution

  • Use list()

    gridline = []
    for i in range(5):
        gridline.append("")
    grid = []
    for i in range(5):
        grid.append(list(gridline))