0

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?

SignalProcessed
  • 371
  • 4
  • 16
  • 2
    Also: yes, you are missing something conceptually - checker won't work because the index error happens when resolving the argument to the function, so *the function never gets called*. – jonrsharpe Oct 19 '18 at 07:14
  • Since it happens when resolving the argument, does that mean my issue is inherently with the list class? Would my most effective route be creating my own list sub-class method? – SignalProcessed Oct 19 '18 at 07:31
  • *"Most effective"* is something you'll need to work out for your context. It could be a subclass, it could be passing the indices to the function, it could be padding the lists to start with. – jonrsharpe Oct 19 '18 at 07:53

0 Answers0