0

I'm designing a Mastermind game, which basically compares 2 lists and marks the similarities. When a colour is found at the right place, a flag making the correct position is added and the item found on the reference list is marked off. The reference list is feeding off an array from another function. The problem is at the mark off, as any changes done to the reference list is changing also the original array, which i don't want it to happen

tempCode = mCode  #mCode is the array combination randomly generated from another function 

for i in range (len(uCode)): #user input array
        for j in range (len(tempCode)): #temp array
            if uCode[i] == tempCode[j]: # compare individual chars
                if i == j: #compare position
                    flagMark = "*" 
                    tempCode.insert(j+1, "x") #problem starts here
                    tempCode.remove(tempCode[j])
                    fCode.append(flagMark)

When the insert is reached both the tempCode and mCode change which it is not intended.

The code is written in a way should the user enter a combination of the same colours, thus checking the chras(the colours are just letters) and the position, and then mark them of with "x"

As it stands, when it gets to

tempCode.insert(j+1, "x")

the arrays will change to

mCode = ["B","R","x","G","Y"]
tempCode = ["B","R","x","G","Y"]

when I would just want

mCode = ["B","R","G","Y"]
tempCode = ["B","R","x","G","Y"]
Ben_A_135
  • 153
  • 1
  • 1
  • 5
  • Possible duplicate https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list –  Oct 26 '19 at 17:20

1 Answers1

1

See also this answer, which is a different presentation of the same problem.

Essentially, when you do tempCode = mCode, you're not making a copy of mCode, you're actually making another reference to it. Anything you do to tempCode thereafter affects the original as well, so at any given time the condition tempCode == mCode will be true (as they're the same object).

You probably want to make a copy of mCode, which could be done in either of the following ways:

tempCode = mCode.copy()
tempCode = mCode[:]

which produces a different list with the same elements, rather than the same list

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53