1

I'm a bit new to python and cannot figure out why my variable GTRed gets overwritten where indicated. As far as my understanding goes GTRed should stay untouched at that point. I'm aware that I can reduce the number of nested for loops by using something like 'for x,y in xygrid:', but that should not affect this.

Thank you very much indeed for any help.

Kind regards

GTN = 0
GTRed = [[0 for j in range(5)] for i in range(4)]
GTYH = [[0 for j in range(5)] for i in range(4)]
for jred in range(4):
    for ired in range(3):
        GTRed = [[0 for j in range(5)] for i in range(4)]
        GTRed[ired][jred]=11
        GTRed[ired+1][jred]=1
        GTRed[ired][jred+1]=1
        GTRed[ired+1][jred+1]=1
        for jyh in range(4):
            for iyh in range(2):
                GTYH = GTRed
                if GTYH[iyh][jyh]==0 and GTYH[iyh+1][jyh]==0:
                    print GTRed
                    GTYH[iyh][jyh]=22 
                                        # The above line seems to somehow  affect GTRed
                    print GTRed
                    GTYH[iyh+1][jyh]=2
                    GameTable[GTN] = GTYH
                    GTN = GTN + 1

2 Answers 2

3

The problem is in the line

GTYH = GTRed

These two variables point to the same list of lists.

a = [0,1,2]
b = a
b[1] = 100
print a # prints [0, 100, 2]

A solution (for a list of lists) would be

GTYH = [x[:] for x in GTRed]

or

import copy

GTYH = copy.deepcopy(GTRed)
Sign up to request clarification or add additional context in comments.

Comments

-1

as the above poster said, the line GTYH = GTRed

tells GTYH to access the same list as referred to by GTRed

tou could try GTYH = GTRed[:]

this would create a new instance of the list

1 Comment

GTRed is a list of lists. Simple GTRed would create a new list of the old lists.

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.