user75747475 user75747475 - 1 year ago 62
Python Question

Checking if position in a list of lists is true or false

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
return False

Answer Source

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
        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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download