python - Default value for out-of-bounds list index -


is there standard approach getting item list returning default value is out-of-bounds?

just example have function (well, many variants of this, newest reading csv files):

def list_get_def( lst, ndx, def_val ):   if ndx >= len(lst):     return def_val   return lst[ndx] 

use try-except block , catch indexerror.

>>> def testfunc(lst, index):         try:             return lst[index]         except indexerror:             return "abc"   >>> testfunc([1, 2, 3], 2) 3 >>> testfunc([1, 2, 3], 9) 'abc' 

a similar question here discusses why lists don't have get method dictionaries do.

if want use if statement, can using single line of code.

>>> def testfunc(lst, index):         return lst[index] if index < len(lst) else "abc"  >>> testfunc([1, 2, 3], 2) 3 >>> testfunc([1, 2, 3], 9) 'abc' 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -