Pointers in Python

Laszlo Nagy gandalf at shopzeus.com
Tue Apr 27 09:30:01 EDT 2010


> Hi, I can't figure out how can I change the variable type in function.
> In C I could do that easily by changing pointer.
>   
Please read about "mutable and immutable objects in Python". If you 
understand the difference between them, you will get the idea. I'll 
explain program anyway, showing you need to think differently.
> Code:
> def add(b):
>
>     b = {}
>   
Here you create a new dict objects, and rebind the local name 'b' to 
this newly created object.
>     print type(b)
>
> a = []
>   
Here you create a new list object, and bind the global name 'a' to this 
object.
> print type(a)
> add(a)
>   
You call your function here, passing the list object you have previously 
created. The list object won't be changed (and in fact, won't be used at 
all).
> print type(a)
>
>   
Now, if try to rewrite your example like this:

def add(b):
	b.append(10) # Call append() on b -> change its state!

a = []
print a
add(a)
print a # Prints [10]


Look how the list object was changed.

If you use an immutable object, it is totally different:


def add(b):
	b = b + 2

a = 10
print a
add(a)
print a # Prints 10


It is because inside the add() function, you do not CHANGE the state of the integer object. Instead of that, you create a new integer object, and rebind that to a local variable name. State of certain objects cannot be changed at all. They are called immutable. Integers, floats, strings are immutable. Other objects are mutable: lists, dicts etc.

This is a big difference between C and Python. In C, variable names are just pointers to memory locations. In Python, they are references to objects. 

I'm sure others will also answer your question...

Best,

   Laszlo





More information about the Python-list mailing list