-3

I'm trying to write a function that takes three arguments: a list of lists and two indexes i and j that should be both positive. The function should return True if the corresponding element exists within the list and return False otherwise. My idea was to assign mylist[i][j] to some variable, if this element exists within the list it will return True otherwise an exception arises in which case the exception is handled in the second block which returns False. The problem is that when I called this function by giving it two valid indexes it didn't return True instead it returned None.

def isvalid(i, j, mylist):
   if i > 0 and j > 0:
       try:
          l = mylist[i][j]
          return True
       except:
          return False 

l = [[1,2,3], [4,5,6]]
print(isvalid(0,0,l))
None

       
user202729
  • 3,358
  • 3
  • 25
  • 36
vd743r
  • 13
  • 2

1 Answers1

0

Your if statement requires i,j > 0 but you set both to 0. Thus it never runs the try/except. Change to >= and this will work! :-)

def isvalid(i, j, mylist):
   if i >= 0 and j >= 0:
       try:
          l = mylist[i][j]
          return True
       except:
          return False 

l = [[1,2,3], [4,5,6]]
print(isvalid(0,0,l))

OUTPUT: True

astrochun
  • 1,642
  • 2
  • 7
  • 18