default value for list access?
Bo Peng
bpeng at rice.edu
Sun Feb 27 16:39:04 EST 2005
> 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.
You are right that if I use all dictionaries, I can use
a.setdefault(4,{}).setdefault(2,0)
to access a[4][2]. Not too bad compared to the getItem function.
However, this is an scientific application. Data are stored internally
in C format and exposed to Python as python array (arraymodule). I guess
the best way is to modify the arraymodule interface and stop it from
raising an exception when index is out of range. (similar to Ruslan's
solution). But this means too much trouble for now.
I will use the df(a, idx, default) method and see if its performance is
acceptable.
Thanks.
Bo
More information about the Python-list
mailing list