0

I have the following code in python:

gates=[16, 16, 24, 24, 24, 27, 32, 32, 32, 32, 32, 32, 40, 40, 40, 56, 56, 64, 96];
a=gates;
one=a[0];
b=a;
for i in range(0,len(a)):
    b[i]=a[i]/one

Now, at the end of this, I get the following as the output of 'b', as expected:

>>> b
[1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 6]

But I expect that 'a' is unchanged.. but it has changed too.

>>> a
[1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 6]

And to my surprise, 'gates' has changed too!

>>> gates
[1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 6]

Any clues on how to retain 'a' and 'gates' intact? Thanks!

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Nanditha
  • 309
  • 1
  • 6
  • 14

2 Answers2

3

All of them are references to the same object, so modifying any one of them will affect all references:

>>> gates=[16, 16, 24, 24, 24, 27, 32, 32, 32, 32, 32, 32, 40, 40, 40, 56, 56, 64, 96];
>>> import sys
>>> sys.getrefcount(gates)  #reference count to the object increased
2
>>> a = gates
>>> sys.getrefcount(gates)  #reference count to the object increased
3
>>> b = a
>>> sys.getrefcount(gates)  #reference count to the object increased 
4

If you want a new copy then assign the new variables to a shallow copy using [:]:

>>> a = [1, 2, 3]
>>> b = a[:]
>>> a[0] = 100
>>> a
[100, 2, 3]
>>> b
[1, 2, 3]

If the list contains mutable objects itself then use copy.deepcopy.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
2

try this:

a = gates[:]
b = a[:]

these will make a copy of gates and a lists

vahid abdi
  • 9,636
  • 4
  • 29
  • 35