2

Why did the value of item2 change after line 20? No where in the code have I redefined item2 so my expectation is it should not change. Is there any way to run the same code without changing the value of item2? Here is my code:

import  random   

def one(length):
    a = []
    for i in range(length):
        a.append(1)
    return(a)

def two(parent):
    b = parent
    if random.randint(0,10)<11:
        index = random.randint(0,6)
        b[index] = 6
    return b

item1 = one(6)
print(item1)
item2 = item1
print(item2)
item3 = two(item1)
print(item2)

And this is the result I'm getting:

[1,1,1,1,1,1]

[1,1,1,1,1,1]

[1,6,1,1,1,1]
vielkind
  • 2,840
  • 1
  • 16
  • 16
gokul gupta
  • 330
  • 4
  • 13

1 Answers1

0

change b = parent to b = parent[:] in line 10, answer provided by @rakesh

gokul gupta
  • 330
  • 4
  • 13