[Tutor] Lists of duplicates

boB Stepp robertvstepp at gmail.com
Thu Mar 9 00:14:40 EST 2017

On Wed, Mar 8, 2017 at 10:29 PM, Alex Kleider <akleider at sonic.net> wrote:
> On 2017-03-08 17:03, Alan Gauld via Tutor wrote:

>> My first reaction was to sort the initial list then iterate
>> over it creating a new sublist for each change of value.
>> But, it only works for homogenous lists. For mixed types
>> I'd probably opt for a dictionary:
>> def f(lst):
>>     res = {}
>>     for item in lst:
>>         res.setdefault(item,[]).append(item)
>>     return list(res.values())

> The above works BUT
> how????
> Things like this can usually be broken down into their component parts but
> I've been unsuccessful doing so:

Alex, I think you can break this down as follows:

py3: res = {}
py3: def key_item_to_res(item):
...     res.setdefault(item, []).append(item)
py3: key_item_to_res(3)
py3: res
{3: [3]}
py3: key_item_to_res(3)
py3: res
{3: [3, 3]}
py3: key_item_to_res(2)
py3: res
{3: [3, 3], 2: [2]}

I think you can play with this and see how Alan's code works.  The
setdefault(item, []) method checks the dictionary it is acting on for
the key, "item".  If it finds it then it will execute the
"append(item)" method on the sublist attached to that key.  If it does
not find it, then it creates a new key, "item", attaches the empty
list, "[]", to that key, and then appends item to that empty list.


More information about the Tutor mailing list