'Verifying an index exists in Python lists and multidimensional lists
I have a list of indexes that are either:
// Depending on type of list and inputs
single list index check: (x)
2d list index check: (x, y)
3d list index check: (x, y, z)
A variable takes in those indexes mentioned above and then I need to verify that the index exists in the specific list (which can be 1, 2, 3 or more dimensions):
// Examples of lists to check
list_1d = [1, 2, 3]
list_2d = [(1,1), (1, 2), ...]
etc.
I need a function or way to tell if my input index check with the list of indexes has a value in the actual list. Like for example, in a two dimensional list I get (1, 2) passed in I need to verify if there is an index at [1][2] with a true or false. Is there a simple way to do this?
Solution 1:[1]
You could try iterating through every single index and, for each one, try to retrieve the value that corresponds, which can then be used in the next iteration. If any of them fail, then it should return False.
def check_indexes(list_indexes, multidimentional_list):
""" Checks if a list of indexes recursively exist for a multi-dimentional list
"""
current_list = multidimentional_list
for index in list_indexes:
try:
current_list = current_list[index]
except IndexError:
return False
return True
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cblopez |
