nukl
nukl

Reputation: 10511

assign references

Is there a way to assign references in python?

For example, in php i can do this:

$a = 10;
$b = &$a;
$a = 20;

echo $a." ".$b; // 20, 20 

how can i do same thing in python?

Upvotes: 2

Views: 2483

Answers (2)

ikostia
ikostia

Reputation: 7587

In python, if you're doing this with non-primitive types, it acts exactly like you want: assigning is done using references. That's why, when you run the following:

>>> a = {'key' : 'value'}
>>> b = a
>>> b['key'] = 'new-value'
>>> print a['key']

you get 'new-value'. Strictly saying, if you do the following:

>>> a = 5
>>> b = a
>>> print id(a) == id(b)

you'll get True.

But! Because of primitive types are immutable, you cant change the value of variable b itself. You are just able create a new variable with a new value, based on b. For example, if you do the following:

>>> print id(b)
>>> b = b + 1
>>> print id(b)

you'll get two different values.

This means that Python created a new variable, computed its value basing on b's value and then gave this new variable the name b. This concerns all of the immutable types. Connecting two previous examples together:

>>> a = 5
>>> b = a
>>> print id(a)==id(b)
True
>>> b += 1
>>> print id(b)==id(a)
False

So, when you assign in Python, you always assign reference. But some types cannot be changed, so when you do some changes, you actually create a new variable with another reference.

Upvotes: 12

MAK
MAK

Reputation: 26586

In Python, everything is by default a reference. So when you do something like:

x=[1,2,3]
y=x
x[1]=-1
print y

It prints [1,-1,3].

The reason this does not work when you do

x=1
y=x
x=-1
print y

is that ints are immutable. They cannot be changed. Think about it, does a number really ever change? When you assign a new value to x, you are assigning a new value - not changing the old one. So y still points to the old one. Other immutable types (e.g. strings and tuples) behave in the same way.

Upvotes: 2

Related Questions