lets say we have 2d array:
ar = [[1,2],
[3,4]]
if ar[1][1]:
#works
if not ar[3][4]:
#breaks!!
since I am new to python, need to know what is the elegant syntax.
lets say we have 2d array:
ar = [[1,2],
[3,4]]
if ar[1][1]:
#works
if not ar[3][4]:
#breaks!!
since I am new to python, need to know what is the elegant syntax.
Python's much loved EAFP approach with exception handling would be my way of doing it.
try:
print(ar[i][j]) # i -> row index, j -> col index
except IndexError:
print('Error!')
Another way, also known as the LYBL approach, would be using if
checks:
if i < len(ar) and j < len(ar[i]):
print(ar[i][j])
And here's the "one liner" version (that kills readability, but you seem to want):
print(ar[i][j] if i < len(ar) and j < len(ar[i]) else "Error")
If this is a check you need to do often, you could make yourself a little helper function so your main code flows better:
def has_item_at(items, i, j):
return i < len(items) and j < len(items[i])
def main():
items = [[1, 2], [3, 4]]
if has_item_at(items, 1, 1):
# do stuff
if has_item_at(items, 3, 4):
# don't do stuff
If you need to check for existence and also retrieve the item, you could do something like this instead:
def get_item(items, i, j, default=None):
if i < len(items) and j < len(items[i]):
return items[i][j]
return default
def main():
items = [[1, 2], [3, 4]]
item = get_item(items, 1, 1)
if item is not None:
# do stuff