[Tutor] setdefault method

Kent Johnson kent37 at tds.net
Tue Mar 28 03:25:53 CEST 2006


Terry Carroll wrote:

>>>>freq = {}
>>>>sampletext = "norwegian blue"
>>>>for char in sampletext:
> 
> ...   freq[char] = freq.setdefault(char,0)+1

Although I'm a big fan of setdefault() I think this particular example 
is better written as
   freq[char] = freq.get(char,0)+1

There is no need to store the initial 0 into freq as it will immediately 
be overwritten.

Kent



More information about the Tutor mailing list