Help - Search - Members - Calendar
Full Version: Python Array Copying
BleepingComputer.com > Software > Programming
   
PropagandaPanda
Hello.

I'm having some trouble with arrays in Python. From what I understand, when a statement such as the one below is used, the NewArray does not contain a copy of the OldArray, but any references to NewArray are simply redirected to OldArray.
CODE
NewArray = OldArray


This is demontrated:
CODE
Array = [1,1,1,1,1,1]
Arr2 = Array
Array[0] = 99
print Arr2

returns [99, 1, 1, 1, 1, 1]

I can work around this by doing such.
CODE
Array = [1,1,1,1,1,1]
Arr2 = Array[:]
Array[0] = 99
print Arr2


This doesn't work when I want to call a function that has an array as an argument.
CODE
def MakeMove(Board,Rows,Marker,Move):
    Board = Board[:]
    for i in range(0,Rows):
        i = (Rows-1)-i
        if Board[i][Move]==".":
            Board[i][Move] = Marker
            break
    return Board
(Function from a connect 4 game)

Normally, I would use this to actually change the board, in which case it works well.

However, when I want to test a potential new move using this function, it still alters the argument passed to it.

For instance:
CODE
TestBoard = MakeMove(TheBoard[:],Rows,Marker,Move)
TheBoard variable is changed.

Is there some way to avoid this?

Thanks,
The Panda
Romeo29
Try changing the variable names as shown in bold:

def MakeMove(Bord,Rows,Marker,Move):
Board = Bord[:]
PropagandaPanda
Thanks, but I figured it out smile.gif .

QUOTE
import copy
MakeMove(copy.deepcopy(Board),Rows,Marker,Move):


I tried changing the variable name yesterday, but it didn't work.

With Regards,
The Panda
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2010 Invision Power Services, Inc.