list comprehension

Duncan Booth duncan.booth at invalid.invalid
Tue Jan 24 18:32:12 CET 2006

Patrick Maupin wrote:

> Duncan Booth wrote:
>> I prefer writing an 'if' statement here, Bryan prefers 'get', that's
>> just a choice of style. But 'setdefault' here, that has no style.
> Well, I'm often told I have no style, and I _did_ admit that it's an
> abuse of setdefault.  However, I often use setdefault to populate
> nested dictionaries, or dictionaries of sets or lists, e.g.:
> for x, y in somebiglist:
>     bigdict.setdefault(x,set()).add(y)   # Strips duplicates
> for x, y in somebiglist:
>     bigdict.setdefault(x,[]).append(y)   # Preserves duplicates
> To my mind, this latter is so much cleaner and clearer than any of the
> alternatives that it just isn't funny:

Yes, but storing a mutable is a not unreasonable use of setdefault. What I 
objected to was storing an immutable just to overwrite it immediately.

Also, while I agree it is shorter, I'm not convinced that it is much 
cleaner, and it is likely to be slower if there are a lot of duplicates, 
possibly a lot slower if the mutable object has much overhead on its 

More information about the Python-list mailing list