Jump to content


 


Register a free account to unlock additional features at BleepingComputer.com
Welcome to BleepingComputer, a free community where people like yourself come together to discuss and learn how to use their computers. Using the site is easy and fun. As a guest, you can browse and view the various discussions in the forums, but can not create a new topic or reply to an existing one unless you are logged in. Other benefits of registering an account are subscribing to topics and forums, creating a blog, and having no ads shown anywhere on the site.


Click here to Register a free account now! or read our Welcome Guide to learn how to use this site.

Photo

Python Array Copying


  • Please log in to reply
2 replies to this topic

#1 PropagandaPanda

PropagandaPanda


  • Malware Response Team
  • 10,433 posts
  • OFFLINE
  •  
  • Gender:Male
  • Local time:10:30 AM

Posted 16 October 2009 - 10:04 PM

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.
NewArray = OldArray

This is demontrated:
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.
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.
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:
TestBoard = MakeMove(TheBoard[:],Rows,Marker,Move)
TheBoard variable is changed.

Is there some way to avoid this?

Thanks,
The Panda

BC AdBot (Login to Remove)

 


#2 Romeo29

Romeo29

    Learning To Bleep


  • Members
  • 3,194 posts
  • OFFLINE
  •  
  • Gender:Not Telling
  • Location:127.0.0.1
  • Local time:09:30 AM

Posted 17 October 2009 - 09:08 AM

Try changing the variable names as shown in bold:

def MakeMove(Bord,Rows,Marker,Move):
Board = Bord[:]

#3 PropagandaPanda

PropagandaPanda

  • Topic Starter

  • Malware Response Team
  • 10,433 posts
  • OFFLINE
  •  
  • Gender:Male
  • Local time:10:30 AM

Posted 17 October 2009 - 10:06 AM

Thanks, but I figured it out :thumbsup: .

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




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users