1

Ok, with the same program previously I've now hit a problem I should have anticipated; the grid (of variable width and height) is constructed based on a code to alternate the symbols which creates a list, those lists are then stored in the grid as nested lists. below is a section of code for making the list (called line) the odd numbered width is necessary.

1 - + -
2 + - + 
3 - + -

   if gridwidth % 2 != 0: 
        for i in range(gridwidth):
            if i % 2 == 0:
                line.append('-')
            else:
                line.append('+')

Edit - sorry I didn't want to spam with code; the lines are put into the list grid below;

    grid = []
    for i in range(height):
        if i % 2 == 0:
            grid.append(line)
        else:
            grid.append(linerev)

line is then appended to grid by the range(height) and there is another block of code to handle the alternating lines which creates another list (linerev) - my problem is that because of how the grid is created, if I try to change a value in it say turn grid[0,0] into a + or -, it changes it along several rows as grid[1,0], grid[5,0] etc are all referring the the same list - is there any way to avoid this without using global variables, deep copy, or drastically revising how the grid is created? Any help would be much appreciated.

4
  • 1
    you aren't showing enough code. We need to see how you added line to grid. Commented Oct 2, 2011 at 3:46
  • sorry! hopefully that's better? Commented Oct 2, 2011 at 3:52
  • If you want to avoid spamming with code, you should remove irrealvent pieces of code, not parts that directly impinge on the question at hand. Commented Oct 2, 2011 at 3:56
  • cool taken on board, I guess I thought that the construction of the lists within the lists was somehow more relevant. Thanks for your help. Commented Oct 2, 2011 at 4:02

1 Answer 1

3

The easiest way is to make copies of the lists when you add them:

grid = []
for i in range(height):
    if i % 2 == 0:
        grid.append(line[:])
    else:
        board.append(linerev[:])
Sign up to request clarification or add additional context in comments.

1 Comment

Cheers, I hadn't even thought of doing that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.