In Python 3, how would you go about returning some default value if you have an out-of-bounds index element? This is a similar question to other threads on here, however, mine is a special case. I want to generate a list of list elements with this property on each element.
I tried like so (this is a generalization of my code):
list2 = [list1[0][0] or None,
list1[0][1] or None,
list1[1][0] or None,
list1[1][1] or None]
[Note: my indices don't necessarily have a pattern like above]
I didn't really expect this to work, and it didn't. I get an IndexError: List index out of range
I thought potentially a try/except would work, but that only catches when the whole list2
prompts an IndexError, and not each individual element of list1
.
My last attempt was doing a bit of both, and creating a function that would call on each of list1
with a try/except:
def checker(element):
try:
return element
except IndexError:
return None
list2 = [checker(list1[0][0]),
checker(list1[0][1]),
checker(list1[1][0]),
checker(list1[1][1])]
I still receive the IndexError, however.
Is there a nice way of accomplishing this? Am I missing something conceptually?