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]))
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.