0

In this snippet of code, I would like to make changes to a list, print it out, and then print out the original. I am changing listB, and leaving listC alone. But when I run this code, listC also gets changed for some reason. How can I fix this?

listB = [1,2,3,4,5]
listC = [1,2,3,4,5]
print(listB)
print(listC)
a = 0
while a<100:
    listB[0] = a
    print(listB)
    listB = listC
    print(listB)
    print(listC)
    a+=1
Iredra
  • 143
  • 1
  • 10
  • 3
    `listB = listC` makes `listB` reference the same list as `listC`. You can try using `listB = listC.copy()`. – gen_Eric Sep 08 '20 at 21:03

1 Answers1

0

If two or more lists are assigned like

list1=list2

They are referring to same location.

So when one of the list changes, another list also changes to same

So It's better to have copy list

Try this code

listB = [1,2,3,4,5]
listC = [1,2,3,4,5]
print(listB)
print(listC)
a = 0
while a<100:
    listB[0] = a
    print(listB)
    listB = listC.copy()
    print(listB)
    print(listC)
    a+=1

This code just copies the elements of ListC rather than referencing

So listC stays original ever

KrisH Jodu
  • 104
  • 9