[Tutor] list of dict question
Alan Gauld
alan.gauld at btinternet.com
Mon Oct 11 19:23:28 CEST 2010
"Francesco Loffredo" <fal at libero.it> wrote
>>> 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.
Yes you have to remember that in Python, unlike C etc,
names are not aliases for memory locations. They are keys
into a namespace dictionary. So the value that the dictionary
refers to can change for any given name - even the type of
object can change.
> 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?
Yes and the first and second will be garbage collected since
there is nothing referring to them now.
>>> 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.
Yes and I could have made it even more elegant with:
lst = []
for n in range(3):
lst.append({n:str(n)}) # no explicit object name needed at all!
And even more tight with:
lst = [ {n:str(n)} for n in range(3)]
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list