2

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
DragonKnight
  • 1,740
  • 2
  • 22
  • 35

2 Answers2

7

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")

cs95
  • 379,657
  • 97
  • 704
  • 746
  • 1
    [Explanation of EAFP and LYBL in Python](https://stackoverflow.com/questions/11360858/what-is-the-eafp-principle-in-python). – agtoever Oct 20 '17 at 22:49
  • that should be done in one line :( I was expecting python could show me some power. – DragonKnight Oct 20 '17 at 22:51
  • 3
    @DragonKnight Your one liner: `print(ar[i][j] if i < len(ar) and j < len(ar[i]) else "Error")` I don't recommend it, it kills readability. – cs95 Oct 20 '17 at 22:52
  • thats true, its not readable. i wished `if not ar[3][4]: ` would work elegantly. thanks yall. – DragonKnight Oct 20 '17 at 22:55
0

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