Question

I don't understand this behaviour:

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 list changed, but variable doesn't? How can I change variable in function? Many people say about passing by value, by reference, by object reference, so I am a bit confused and don't know how it is really.

Était-ce utile?

La solution

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

Lists in python are mutable. You pass a list (by reference, as always in python), and the function changes it in place. That's why the change is "seen" externally to the function.

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

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

Autres conseils

Because, lists are mutable but integers are immutable.

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top