83

I have a simple problem in Python that is very very strange.

def estExt(matriz,erro):
    # (1) Determinar o vector X das soluções
    print ("Matrix after:");
    print(matriz);

    aux=matriz;
    x=solucoes(aux); # IF aux is a copy of matrix, why the matrix is changed??

    print ("Matrix before: ");
    print(matriz)

...

As you see below, the matrix matriz is changed in spite of the fact that aux is the one being changed by the function solucoes().

Matrix before:
[[7, 8, 9, 24], [8, 9, 10, 27], [9, 10, 8, 27]]

Matrix after:
[[7, 8, 9, 24], [0.0, -0.14285714285714235, -0.2857142857142847, -0.42857142857142705], [0.0, 0.0, -3.0, -3.0000000000000018]]

martineau
  • 119,623
  • 25
  • 170
  • 301
André Freitas
  • 1,070
  • 1
  • 10
  • 13

3 Answers3

127

The line

aux=matriz;

Does not make a copy of matriz, it merely creates a new reference to matriz named aux. You probably want

aux=matriz[:]

Which will make a copy, assuming matriz is a simple data structure. If it is more complex, you should probably use copy.deepcopy

aux = copy.deepcopy(matriz)

As an aside, you don't need semi-colons after each statement, python doesn't use them as EOL markers.

brc
  • 5,281
  • 2
  • 29
  • 30
  • 3
    Hi, thanks for your answer =) But i have a another question considering this fact: if b=1 and a=b, if we change a=3, the b is not changed in python. Why? Thanks =) – André Freitas Nov 14 '11 at 15:20
  • 8
    Because you're changing `a` to point to a different object (the integer `3`), but not changing `b`, so it still points to `1`. – kindall Nov 14 '11 at 17:16
  • 2
    Exactly what I wanted. Also FYI: if you want to deep copy a `dict` structure, you probably want the `dictionary.copy()` – xtonousou Nov 17 '19 at 18:45
29

Use copy module

aux = copy.deepcopy(matriz) # there is copy.copy too for shallow copying

Minor one: semicolons are not needed.

Shekhar
  • 7,095
  • 4
  • 40
  • 45
  • 2
    Welcome to stackoverflow @AndréFreitas. Usually here, it is considered a good community practice to accept one of the answers (one which you think is best, not necessarily mine). – Shekhar Nov 15 '11 at 08:49
7

aux is not a copy of matrix, it's just a different name that refers to the same object.

Use the copy module to create actual copies of your objects.

omz
  • 53,243
  • 5
  • 129
  • 141