Method returns variable into its original parameter variable
I am encountering a problem with my program, where a method is saving everything that it does to the parameter variable used in it.
Here's an example: method that moves a list's element to the left by given spaces.
def moveLeft (perm, pos, spaces):
permTemp = perm
for n in range(spaces):
charMoved = permTemp[pos-n]
permTemp [pos-n] = permTemp[pos-n-1]
permTemp[pos-n-1] = charMoved
return permTemp
permO = [0,1,2,3] #original perm
print moveLeft(permO, -1, 2)
print moveLeft(permO, -1, 2)
print permO
The expect output would be: the first two to be the same (since i开发者_如何转开发t is printing the same returned values of the method) and the last output to be the original list ( [0,1,2,3] ). Instead I get:
>>>
[0, 3, 1, 2]
[0, 2, 3, 1]
[0, 2, 3, 1]
Use
permTemp = perm[:]
to actually copy the list, instead of just assigning a new name to the same object.
Python assignment does not create new objects, it just names existing ones. That's why you are modifying the original list.
Use Sven's list copy, but note also that you don't need a temporal variable to swap values:
def moveLeft(perm, pos, spaces):
permTemp = perm[:]
for n in range(spaces):
permTemp[pos-n], permTemp[pos-n-1] = permTemp[pos-n-1], permTemp[pos-n]
return permTemp
精彩评论