# Python primer - comments appreciated!

Thorsten Kampe thorsten at thorstenkampe.de
Wed Sep 11 10:09:02 EDT 2002

```*  Terry Reedy
> "Thorsten Kampe" <thorsten at thorstenkampe.de> wrote in message
>> * Terry Reedy
>>>      result.setdefault(func(item),[]).append(item)
>>
>> To make every item hashable, I made this:
>> result.setdefault(repr(func(item)),[]).append(item)

Is repr(seq) a "bulletproof", "canonical" way to make a mutable
sequence hashable and most important for this algorithm:
repr(x) = repr(y) <=> x = y ?

I think so...

>>>      # {}.setdefault(key,default) was added for just this sort of
>>> usage
>>
>> Sorry, I just don't get it: your mixing (chaining?) a dict method
>> and
>> 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.

You mean the value corresponding to the prior non existent key is set
to '[]':

>>> D = {'0': [3, 6], '1': [4]}
>>> D.setdefault('2', [])
[]
>>> D
{'1': [4], '0': [3, 6], '2': []}

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

Okay, let's make this clear:
D = {'0': [3, 6], '1': [4]}
D.setdefault('1', [])
...returns: [4]
[4].append(7)
...puts [4, 7] on the "stack"

But where is the instruction saying "store [4, 7] back to D['1']"?
Shouldn't this be: D['1'] = D.setdefault('1', []).append(7) ?

>> (Mathematically spoken, the quotient set is the set of all
>> equivalence
>> 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.

This is correct. Fortunately the /quotient set/ *is* a set and does
*not* contain duplicates (duplicate equivalence classes). It's a
partition and partitions are always disjoint and non-empty.

Thorsten

```