Python primer - comments appreciated!

Terry Reedy tjreedy at
Tue Sep 10 21:08:59 EDT 2002

"Thorsten Kampe" <thorsten at> wrote in message
news:allpms$1r005a$1 at
> * Terry Reedy
> >      result.setdefault(func(item),[]).append(item)
> To make every item hashable, I made this:
> result.setdefault(repr(func(item)),[]).append(item)
> >      # {}.setdefault(key,default) was added for just this sort of
> Sorry, I just don't get it: your mixing (chaining?) a dict method
> a list method as if it was a f(g(x)) and /it works/!?! Where is that
> documented? How is is that evaluated (left to right)?

Yes, left to right.  Dict.setdefault returns the value corresponding
to the key after setting d[key]=default if key not already in d.  In
this case, *all* values are initialized to [] by such a call.  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().  See
Python Library Reference 2.2.7 for dicts.

> > >>> f = lambda x: x % 3
> > >>> equiv_class([0,1,2,3,4,5,6,7,8,9],f,part='bool')
> Now this is:
> quotient_set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], lambda x: bool(x % 3))
> (Mathematically spoken, the quotient set is the set of all
> classes induced by func, which is what we return)

Since the equivalence lists may have duplicates, they are not,
strictly speaking, sets.  If the set of return values were made to be
dicts (or, in 2.3, sets) instead of lists, then they would be.  Such
details can, of course, be adjusted for a particular application.

Terry J. Reedy

More information about the Python-list mailing list