default value for list access?

Peter Hansen peter at engcorp.com
Sun Feb 27 15:36:54 EST 2005


Bo Peng wrote:
> The data is the count of something, for example a[90]=10. a may be a 
> dictionary if the range is huge and a list when the range is reasonably 
> small. In the dictionary case, I can use a.setdefault(80, 0) if key 80 
> does not exist. In the list case, I have to check the length of list 
> before I access it (or use exception).
> 
> This becomes troublesome when I need to do the following a lot.
> 
>   b = a[80][1] + a[80][2] + a[80][3]
> 
> If I use the getItem function in my previous email, it will look like
> 
>   b = getItem(getItem(a, 80, []), 1, 0) + getItem(getItem(a, 80, []), 2, 
> 0) + getItem(getItem(a, 80, []), 3, 0)
> 
> What would be the best solution to handle this? 

Sounds to me like the best solution is to simplify the implementation
and dispense with the list alternative.  Why use a list if a dictionary
is suitable?  Don't say performance: that's premature optimization.
Dictionaries already have what you need, apparently, with setdefault(),
so just use them and keep the code simple.

...
> but I am afraid that a for loop would bring serious performance problem.

More premature optimization?  The first rule of programming should be
to make it work.  Then consider making it faster, but only if it is
really unacceptably slow.  (Some would say to make it work, then make
it "right", then make it fast.  In this case, "right" doesn't mean
"correct" (that's the first step), it means making it clean and simple.
Doing it this way makes sense only if you have a really good test
suite developed along with the code, ala test-driven development.
Lacking that, you should focus on "right" and working together,
which in this case suggests leaving out the complicated list option.)

-Peter



More information about the Python-list mailing list