2

I'm trying to write a function that analyzes a given list of lists for a specific position and returns True if the position exists and False if it doesn't.

For example, if the list of lists that we'll call "list2" has 7 columns and 5 rows (Basically a list of 5 lists where each list has 7 values and is on its own line), the function should return True if the test case list2[5][4] is run through the function because row 5, and column 4 exists but if the test case list2[8][6] or list2[-5][-1] is run through the function it should return False because row 8 and column 6 don't exist and we can't have negative rows and columns. How could this be accomplished?

This is the code I have so far. When tested it says invalid syntax but I thought I'd include it anyway to help show what my goal is

def in_list(row, col, list):
    if list[row][col] == True 
    return True
    else:
    return False

3 Answers3

1

Indent your code after if and else. And use colons ":"

def in_list(row, col, list):
    if list[row][col] == True:
        return True
    else:
        return False
Progg
  • 85
  • 8
  • Thank you this got rid of the syntax error but it still isn't checking the positions and returning if they are true or false – user75747475 Oct 29 '16 at 14:28
1

If you really want to test for the array item by accessing it, wrap it in a try..except block. If an exception occurs, return False, otherwise return True.

However, there is an easier way--just test that row and col point to a valid entry by using the array's lengths. Here is one way to do that.

def in_list(row, col, lst):
    if 0 <= row < len(lst) and 0 <= col < len(lst[row]):
        return True
    else:
        return False

There are more concise ways, but this should be clear. The "short-cut evaluation" in the if line prevents an exception in the check for col if row is not in range. Note that I changed the parameter name from list to lst: using a built-in name is a bad idea. Note that my code does not check if the value of the entry is True or False, as you code seems to try to do--if you want that, it is easy to add that check to my code. Finally, note that my code also works if the rows of the array have differing numbers of columns, which is possible in Python. My code checks only the requested row, which is suitable for this purpose.

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
0

Once you have fixed your code by adding colons and indenting it as required, you will likely encouter another error: Accessing indices that do not exist is not allowed in python, it doesn't amout to False.

One way of circumventing it would be to enclose your test in a try:... except block.

bli
  • 7,549
  • 7
  • 48
  • 94