Python primer - comments appreciated!
Terry Reedy
tjreedy at udel.edu
Wed Sep 11 10:35:44 EDT 2002
"Thorsten Kampe" <thorsten at thorstenkampe.de> wrote in message
news:alnipo$1pqmu8$1 at ID-77524.news.dfncis.de...
> * Terry Reedy
> > Then
> > append to the list. This working depends on there being *two*
> > references to the list. The one in the dict (possibly new,
possible
> > not) and the one returned by the method and used by append().
Please reread second sentence!!!
> Okay, let's make this clear:
> D = {'0': [3, 6], '1': [4]}
> D.setdefault('1', [])
> ...returns: [4]
It returns a reference to the list with current value [4]
> [4].append(7)
> ...puts [4, 7] on the "stack"
NOOOOO!!!!! In context of of original expression, it appends 7 to
list pointed to by *both* dict and reference returned by setdefault().
> But where is the instruction saying "store [4, 7] back to D['1']"?
The list is never taken out of D['1']. The append is 'in place' via
the double reference!
Try
print id(D['1']), id(D.setdefault('1', []))
to see that same list.
> Shouldn't this be: D['1'] = D.setdefault('1', []).append(7) ?
Since append returns None, this will not work.
Terry J. Reedy
More information about the Python-list
mailing list