Getting a default value on index out of range in Python

zjm1126 picture zjm1126 · Apr 4, 2010 · Viewed 82.2k times · Source
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?

Answer

Thomas picture Thomas · Apr 4, 2010

In the Python spirit of "ask for forgiveness, not permission", here's one way:

try:
    b = a[4]
except IndexError:
    b = 'sss'