Thank you, Alan and Dave, for your spotting this weak point in my understanding of Python!

On 11/10/2010 2.11, Dave Angel wrote:
On 2:59 PM, Alan Gauld wrote:

"Francesco Loffredo" <f...@libero.it> wrote

did, Roelof's code would work perfectly, and you could store in a list
all the subsequent changes of a dictionary without calling them with
different names.

You don;'t need dfifferent names. Provided the name creates a
new object inside the loop you can reuse the same name.
Roeloff's problem was that he only created one object, outside
his loop.

lst = []
for n in range(3):
obj = {}
I didn't know that this creates a new obj if obj already exists, I thought it would just update it. That's my mistake.
Does this mean that if I write:
obj = {}
obj = {}
obj = {}
then I'll create 3 different dictionaries, with the name obj referring to the third?

obj[n] = str(n)
lst.append(obj)

Creats a list of 3 distinct dictionaries but only uses one name - obj.
Ok, this does not lose too much in elegance.

I understand that if .append() stored a copy of the dict in the list,
you will end up with lots of copies and a huge amount of memory used by
your list, but that's exactly what will happen if you make those copies
yourself. But you wouldn't have to devise a way to generate a new name
for the dictionary every time you need to update it.

Python uses references throughout, what you are suggesting would
be a change to the normal way that Python uses names.
I needed a hint about what is "the normal way that Python uses names", thank you.


Probably more importantly, if a language only implemented copies, you
couldn't have references without some different syntax. On the other
hand, with Python, everything's a reference, and if you want a copy, you
make one when you need it. You never do for immutables, and only you
know when you need it for mutable objects.

DaveA
Thank you too, Dave. I thought that to make a copy you would have to create a different name, and this sounded too cumbersome for me...

Francesco
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.862 / Database dei virus: 271.1.1/3188 -  Data di rilascio: 
10/10/10 08:34:00
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to