Passing a variable and list to work in Python

I do not understand this behavior:

def getvariable(v): v += 1 def getlist(l): l.append(8) myvariable = 1 mylist = [5, 6, 7] print myvariable, mylist getvariable(myvariable) getlist(mylist) print myvariable, mylist 

Output:

 1 [5, 6, 7] 1 [5, 6, 7, 8] 

Why did the list change but the variable did not indicate? How to change a variable in a function? Many people talk about passing by value, by reference, by object link, so I'm a little confused and don't know how it is real.

+4
source share
2 answers

In integers, python is immutable. v += 1 only binds the new integer value to the name v , which is local in your function. It does not change the integer in place.

Lists in python are mutable. You pass the list (by reference, as always in python), and the function changes it in place. This is why the change is “visible” externally to the function.

There is no such thing as "pass by value" in python.

What you probably want to do is return v+1 from your function, and not change the value bound to the name v .

+4
source

Since lists are mutable, but integers are immutable.

Read more about this here: http://docs.python.org/2/reference/datamodel.html#objects-values-and-types

+1
source

Source: https://habr.com/ru/post/1481507/


All Articles