[Tutor] Lists of duplicates

Alan Gauld alan.gauld at yahoo.co.uk
Thu Mar 9 04:04:28 EST 2017

On 09/03/17 04:29, Alex Kleider wrote:

>> 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????

setdefault returns the current value for the key
or the default, in this case an empty list.
So we can split it in two as:

for item in lst:
   val = res.setdefault(item,[])

And since setdefault also assigns the default
to the dict if it doesn't exist we don't need
to add an extra assignment.

We could have used get() instead:

for item in lst:
    sub = res.get(item,[])
    res[item] = sub

Is that any clearer?
Breaking setdefault() down gives something like:

   sub = res[item]
except KeyError:
   res[item] = []
   sub = res[item]

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list