On 26/11/14 12:57, Mohamed Ben Mosbah wrote:
Hi I'm new to Python and I would like to know how he deals with memory
space.

Don't even think about it, you will only mislead yourself.
Seriously you shouldn't try to link Python objects to physical
memory locations. And you should certainly never build any
dependencies on locations into your code.

You are operating in a kind of virtual machine with its own ideas of where things are located and any relation to physical memory is purely coincidental.

Just think about objects and names.
Names refer to objects.
Some objects can be changed (mutable) and others can't (immutable).
Objects have an ID; which may or may not be related to their memory location.

I thought I had understood but I made a test and the results were
uncoherent with my understanding, here is the thing:

 >>> a=[1,2]
 >>> l=[a,a]
 >>> id(a); id(l[0]); id(l[1]);
61659528
61659528
61659528

So those references are all to the same object which is a list and
is therefore mutable. l refers to a different list which is also mutable.

 >>> #All Have the same ID
 >>> l[0]=[0,0]

You have now changed the first element of l so it no longer
refers to the same object as a but to a new list [0,0]

 >>> l
[[0, 0], [1, 2]]
 >>> #Why didn't l[1] change as well?

Because you didn't change what l[1] referred to, you only
changed l[0].

 >>> id(a); id(l[0]); id(l[1]);
61659528
61390280
61659528
 >>> #How come id(l[0]) changed?

Because you assigned it to the new list object.

 >>> a = [4,4]

and now you have created yet another list object and
referenced it from 'a'

 >>> l
[[0, 0], [1, 2]]
 >>> #Why didn't l[1] change? l[1] and a were occupying the same memory
adress!

No they weren't, the names 'a' and l[1] were both referring to the
same object but you changed 'a' to refer to a different object.
So they are now different. Python names have nothing to do with
memory locations, they are just references to objects.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to