[Tutor] Lists of duplicates

Alex Kleider akleider at sonic.net
Thu Mar 9 18:58:49 EST 2017


On 2017-03-09 06:07, Steven D'Aprano wrote:
> On Wed, Mar 08, 2017 at 08:29:19PM -0800, Alex Kleider wrote:
> 
>> Things like this can usually be broken down into their component parts
>> but I've been unsuccessful doing so:
>> 
>> def f(lst):
>>     res = {}
>>     for item in lst:
>>         method_res = res.setdefault(item, [])
>>         res.method_res.append(item)
>> #       res.setdefault(item,[]).append(item)
>>     return list(res.values())
>>     res.method_res.append(item)
>> 
>> AttributeError: 'dict' object has no attribute 'method_res'
>> 
>> Python must be doing some trickery behind the scenes.
> 
> Why do you say that? I'm not sure what result you expected, or what you
> are trying to do, but you have:
> 
>     res  # a dict
>     res.method_res
> 
> No surprises that this fails with AttributeError. Dicts do not have an
> attribute or method called "method_res".
> 
> Perhaps you meant to write:
> 
>     # not this
>     # res.method_res.append( ... )
> 
>     # this instead
>     method_res.append( ... )
> 
> 
> although part of the confusion is that "method_res" is a poorly chosen
> name. It isn't a method, it is a list.

Thanks again, Steven.  I confess to having intended to write 
res.method_res.append(...
but your response made me realize that because lists are mutable it all 
works without the res. prefix.

I chose method_res to refer to the fact that it is the result of a 
method call.  A poor choice I admit.



More information about the Tutor mailing list