Can someone explain why the example with integers results in different values for x and y and the example with the list results in x and y being the same object?
x = 42
y = x
x = x + 1
print x # 43
print y # 42
x = [ 1, 2, 3 ]
y = x
x[0] = 4
print x # [4, 2, 3]
print y # [4, 2, 3]
x is y # True
Python's language reference for assignment statements provides the following details: If the assignment target is an identifier, or variable name, then this name is bound to the object. For example, in x = 2 , x is the name and 2 is the object.
Pass by reference means that you have to pass the function(reference) to a variable which refers that the variable already exists in memory. Here, the variable( the bucket) is passed into the function directly.
All values in Python are references. What you need to worry about is if a type is mutable. The basic numeric and string types, as well as tuple and frozenset are immutable; names that are bound to an object of one of those types can only be rebound, not mutated.
The best explanation I ever read is here: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables
Because integers are immutable, while list are mutable. You can see from the syntax. In x = x + 1
you are actually assigning a new value to x
(it is alone on the LHS). In x[0] = 4
, you're calling the index operator on the list and giving it a parameter - it's actually equivalent to x.__setitem__(0, 4)
, which is obviously changing the original object, not creating a new one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With