0

Take a look at the following code.

import random
devicelist = ['a','a','a','a','a']

def generateconfig(tempconfiguration):
 global devicelist
 indexpositionzero = []
 indexpositionone = []
 for index in range(len(devicelist)):
  if tempconfiguration[index] == 1:
   indexpositionone.append(index)
  else:
   indexpositionzero.append(index)
 if len(indexpositionone) >= 3:
  godown = True
 elif len(indexpositionone) == 0:
  godown = False
 else:
  godown = random.randrange(0,2,1)
 if godown == True:
  index = random.randrange(0,len(indexpositionone),1)
  tempconfiguration[indexpositionone[index]] = 0
 if godown == False:
  index = random.randrange(0,len(indexpositionzero),1)
  tempconfiguration[indexpositionzero[index]] = 1
  return tempconfiguration

x = [1,0,1,0,1]
y = generateconfig(x)

print x
print y

Running this code will change x to the same value of y. Why is this happening? I'm not touching x at all! Such confuse! Please help.

myopenid
  • 374
  • 3
  • 6
  • Python variables are *references*. You passed in the list object `x` referenced, then altered that object in the function. – Martijn Pieters Jan 29 '15 at 08:38
  • A list (mutable object) is passed by reference, so `tempconfiguration` is a reference to `x`. Try passing `x[:]` instead. See also `copy.deepcopy()` – cdarke Jan 29 '15 at 08:38
  • @MartijnPieters Do you have any idea how do I remove the reference? If say, I do a `newtempconfiguration = tempconfiguration` within the function and manipulate `newtempconfiguration`, `x` is still changed! – myopenid Jan 29 '15 at 08:42
  • @myopenid: see [How to clone or copy a list in Python?](http://stackoverflow.com/q/2612802) – Martijn Pieters Jan 29 '15 at 08:54
  • figured out another way to do this by `for index in range(len(seperatecopyofconfiguration)): tempconfiguration.append(seperatecopyofconfiguration[index])` – myopenid Jan 29 '15 at 14:50

0 Answers0