0

i've come across to a situation where my values are getting changed without my knowledge.

def randomizer(task):
maintask = task
x = 0
k = 1
while 1:
    x += 1
    if x > len(task):
        break
    if k == 0:
        task.pop(x)
        x -= 1
        k = 1
    else:
        k = 0
#task.reverse()
#task = task + maintask
print("task ----- ", task)
print("maintask ----- ", maintask)

Above given is my python script. My expectation was "task" would be different from "maintask". But both gave same value to me. below given is the output.

task ----- [(9, 'CR12345'), (8, 'CR12346'), (3, 'CR63943'), (4, 'IM46667'), (2, 'THIS IS SE COND')]

maintask ----- [(9, 'CR12345'), (8, 'CR12346'), (3, 'CR63943'), (4, 'IM46667'), (2, 'THIS IS SE COND')]

I think this is the because "=" is working based on passing by reference. I need to pass the value which should not change after changing the parent variable ("task" here)

hhsecond
  • 62
  • 7
  • Also https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python – Cory Kramer Aug 18 '15 at 13:07
  • @CoryKramer: yup, but the gist is covered in the dupe target I picked. – Martijn Pieters Aug 18 '15 at 13:07
  • Thank you Mrtijin for the quick reply. i've been through that link already. but being a tyro, i couldnt understand much. And the link posted by corykramer (thank you so much) is the exact succinct answer that i wanted. But Martijn's link would be helpful for learning in and out of this problem. – hhsecond Aug 18 '15 at 13:12
  • Ah, rereading I see that there is no explicit *pass in a copy* section. Yes, Cory's link shows how to create a copy of a list rather than to pass in the list object itself. – Martijn Pieters Aug 18 '15 at 13:26

0 Answers0