oops
oops

Reputation: 21

Why does my variable get overwritten in nested for loops in python?

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

Upvotes: 1

Views: 734

Answers (2)

Sam Sharp
Sam Sharp

Reputation: 359

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

Upvotes: -1

eumiro
eumiro

Reputation: 213075

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)

Upvotes: 3

Related Questions