Default return values for out-of-bounds list item

MRAB python at mrabarnett.plus.com
Fri Jan 22 03:41:05 CET 2010


gburdell1 at gmail.com wrote:
> Is there a built-in method in python that lets you specify a "default"
> value that will be returned whenever you try to access a list item
> that is out of bounds? Basically, it would be a function like this:
> 
> def item(x,index,default):
>    try:
>       return x[index]
>    except IndexError:
>       return default
> 
> So if a=[0,1,2,3], then item(a,0,44)=0, item(a,1,44)=1, and item(a,
> 1000,44)=44, item(a,-1000,44)=44
> 
> What I want to know is whether there is a built-in method or notation
> for this.
 >
There's no built-in method or notation for that.

 > What if, for example, we could do something like a [1000,44] ?

That's actually using a tuple (1000, 44) as the index. Such tuples can
be used as keys in a dict and are used in numpy for indexing
multi-dimensional arrays, so it's definitely a bad idea.

If such a method were added to the 'list' class then the best option (ie
most consistent with other classes) would be get(index, default=None).



More information about the Python-list mailing list