a=['123','2',4]
b=a[4] or 'sss'
print b
I want to get a default value when the list index is out of range (here: 'sss'
).
How can I do this?
a=['123','2',4]
b=a[4] or 'sss'
print b
I want to get a default value when the list index is out of range (here: 'sss'
).
How can I do this?
In the Python spirit of "ask for forgiveness, not permission", here's one way:
try:
b = a[4]
except IndexError:
b = 'sss'
try:
b = a[4]
except IndexError:
b = 'sss'
A cleaner way (only works if you're using a dict):
b = a.get(4,"sss") # exact same thing as above
Here's another way you might like (again, only for dicts):
b = a.setdefault(4,"sss") # if a[4] exists, returns that, otherwise sets a[4] to "sss" and returns "sss"
In the non-Python spirit of "ask for permission, not forgiveness", here's another way:
b = a[4] if len(a) > 4 else 'sss'
You could also define a little helper function for these cases:
def default(x, e, y):
try:
return x()
except e:
return y
It returns the return value of the function x
, unless it raised an exception of type e
; in that case, it returns the value y
. Usage:
b = default(lambda: a[4], IndexError, 'sss')
Edit: Made it catch only one specified type of exception.
Suggestions for improvement are still welcome!
I’m all for asking permission (i.e. I don’t like the try
…except
method). However, the code gets a lot cleaner when it’s encapsulated in a method:
def get_at(array, index, default):
if index < 0: index += len(array)
if index < 0: raise IndexError('list index out of range')
return array[index] if index < len(a) else default
b = get_at(a, 4, 'sss')