+ 5

needed help with a code why does changing b changes a as well

a=[2,2,2,2,2,2,2] k=2 b=a count=0 for i in range(1,len(a)): b[i]=b[i-1]+k for i in range(len(a)): if a[i]==b[i]: pass else: count+1 print(a,b)

19th Jun 2018, 2:17 PM
Jayesh Bhushan
Jayesh Bhushan - avatar
5 odpowiedzi
+ 3
Becase "b" its a reference of "a" content (a list)... You have to copy the list like: b= a[:]
19th Jun 2018, 2:19 PM
KrOW
KrOW - avatar
+ 11
good
25th Jun 2018, 3:34 AM
Archana
+ 3
a = [1, 2, 3] b = a b == a # True b is a # True In the above, b and a point to the same places in memory. Changing one will change the other because they are the same. c = a[:] c == a # True c is a # False In the above c has the same values as a, but they’re saved in a different place in memory. Then you can change one list without changing the other.
19th Jun 2018, 5:36 PM
Pedro Demingos
Pedro Demingos - avatar
+ 3
thanks guys
20th Jun 2018, 9:26 AM
Jayesh Bhushan
Jayesh Bhushan - avatar