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
  • 756,363
  • 169
  • 1,062
  • 1,111
Nanditha
  • 199
  • 1
  • 5
  • 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
  • 232,417
  • 55
  • 437
  • 487
2

try this:

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

these will make a copy of gates and a lists

vahid abdi
  • 8,650
  • 4
  • 29
  • 35