[Tutor] list of dict question

Dave Angel davea at ieee.org
Mon Oct 11 02:11:40 CEST 2010


  On 2:59 PM, Alan Gauld wrote:
>
> "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)
>     lst.append(obj)
>
> 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.
>
> HTH,
>
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



More information about the Tutor mailing list