[Tutor] list of dict question

Alan Gauld alan.gauld at btinternet.com
Sun Oct 10 23:04:30 CEST 2010

"Francesco Loffredo" <fal at 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 = {}
     obj[n] = str(n)

Creats a list of 3 distinct dictionaries but only uses one name - obj.

> 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.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list