Getting a default value on index out of range in Python [duplicate] Getting a default value on index out of range in Python [duplicate] python python

Getting a default value on index out of range in Python [duplicate]


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

try:    b = a[4]except IndexError:    b = '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'


In the Python spirit of beautiful is better than ugly

Code golf method, using slice and unpacking (not sure if this was valid 4 years ago, but it is in python 2.7 + 3.3)

b,=a[4:5] or ['sss']

Nicer than a wrapper function or try-catch IMHO, but intimidating for beginners. Personally I find tuple unpacking to be way sexier than list[#]

using slicing without unpacking:

b = a[4] if a[4:] else 'sss'

or, if you have to do this often, and don't mind making a dictionary

d = dict(enumerate(a))b=d.get(4,'sss')