1

In below code, I expect to get :

[[1, 4, 6], [2, 3, 6], [2, 4, 5]]

But it return :

[[1, 3, 5], [1, 3, 5], [1, 3, 5]]

There are two problems :

  • word in function b is a reference, not a new variable!!
  • everything put in the child is a reference!!

My code :

def b(word,i):
    word[i] = word[i]-1
    return word
def a(individual):
    child = []
    for i in range(len(individual)):
        child.append(b(individual,i))
    return child
print(a([2,4,6,8]))
parvij
  • 1,381
  • 3
  • 15
  • 31
  • 2
    You already answered to your own question. You need to passby value: https://stackoverflow.com/questions/845110/emulating-pass-by-value-behaviour-in-python – tangoal Aug 01 '18 at 10:53

1 Answers1

2

Just change your b function to this:

def b(word,i):
    tmp = word.copy()
    tmp[i] = tmp[i]-1
    return tmp

Because when you actually change the individual list it will be change all over the program, I mean your code is write but when you change 2 to 1 it changes all over the program. for better understanding add a print('child') after the append.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59