How to modify a list inside a method in Python?

0

Suppose I have the following method and the following list:

def ModificaValores(Valores):
      dados = [6,5,4,3,2,1,0]

      Valores = dados

Valores = [0,1,2,3,4,5,6]

print(Valores)
ModificaValores(Valores)
print(Valores)

Why in the output I have the following result:

[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]

If I modify element by element works, but not so. Explain to me why this happens!

    
asked by anonymous 22.01.2018 / 12:22

1 answer

1

It does not work because the changes made within the scope of the function are not replete to the external scope - nor should it, as this could generate side effects and make it very difficult to maintain the code. That is, do not do this unless it really makes sense .

Let's break it down.

Out of function, in global scope, you define the Valores list. At this point, the Valores object will have a unique identifier representing it that can be obtained via id(Valores) . In CPython, this value represents the memory address of your object. This object is passed via parameter to the ModificaValores function, and as in Python the list type is a changeable type < a>, the object will be passed by reference, which implies that inside the function will be the same object that was created outside, with the same values and same memory address. The fact of being passed via reference explains why you should reflect the changes made element by element, since you are only modifying the object. Even if it reflects the changes to the external scope, it should be used very cautiously, only in cases that really make sense. In general, the ideal would be to return a new list and assign it to the desired object. Something like:

def ModificaValores(Valores):
    # Neste caso o parâmetro é desnecessário
    # mas mantive por questões didáticas
    dados = [6,5,4,3,2,1,0]
    return dados

Valores = [0,1,2,3,4,5,6]

print(Valores)
Valores = ModificaValores(Valores)
print(Valores)

See working at Ideone | Repl.it

And why does not it work when you assign the new list?

Because when you define dados as a new list, you define a new object in memory with a new address, which will exist only in the scope of the function. When you assign dados to Valores , you break the reference that Valores had with the external object and begin to reference the dados local object, however this change is done in the local scope, not being reflected to the scope external - in other words, you have an object Valores in the global scope and another object in the local scope, being different from each other. The changes you make to Valores , in the local scope, will not be reflected in Valores of the global scope, since they are different objects.

    
22.01.2018 / 12:40