Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python references

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
like image 636
hekevintran Avatar asked May 09 '10 08:05

hekevintran


People also ask

What is reference in Python with example?

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.

How do you use reference variables in Python?

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.

Are all types reference types in Python?

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.


2 Answers

The best explanation I ever read is here: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables

like image 73
LeMiz Avatar answered Sep 22 '22 14:09

LeMiz


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.

like image 25
Max Shawabkeh Avatar answered Sep 19 '22 14:09

Max Shawabkeh