Default return values for out-of-bounds list item

Peter Otten __peter__ at web.de
Fri Jan 22 03:21:48 EST 2010


Steven D'Aprano wrote:

> On Thu, 21 Jan 2010 17:56:00 -0800, 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?
> 
> No.
> 
> 
>> Basically, it would be a function like this:
>> 
>> def item(x,index,default):
>>    try:
>>       return x[index]
>>    except IndexError:
>>       return default
> 
> That's probably the best way to do it.
> 
> 
>> 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. What if, for example, we could do something like a [1000,44] ?
> 
> You can use slicing instead:
> 
>>>> a=[0,1,2,3]
>>>> a[2:3]
> [2]
>>>> a[100:101]
> []
> 
> 
> and then detect the empty list and use default:
> 
> def item(x, index, default):
>     a = x[index:index+1]
>     return a[0] if a else default

You need to special-case -1:

>>> for i in range(-4, 4):
...     print "x[%d] -> %r" % (i, item("abc", i, "default"))
...
x[-4] -> 'default'
x[-3] -> 'a'
x[-2] -> 'b'
x[-1] -> 'default'
x[0] -> 'a'
x[1] -> 'b'
x[2] -> 'c'
x[3] -> 'default'

Peter



More information about the Python-list mailing list