Title: merge 'if out of range' and 'if item equals' in one condition
Tags: python
Question: ```   if col-2 &gt; 0:
       if matrix[row, col-2] != 0:
           col -= 2
           # some code here 1 
       else:
           # some code here 2
   else:
       # some code here 2
```

I have many pieces of code like this. Not exactly like this one, but many conditions in my code work the same way. I'd like to merge ```if col-2 &gt; 0:``` and ```if matrix[row, col-2] != 0:``` to get rid of many duplicated lines all over the code (# some code here 2). The problem of merging is checking if an item is non-zero even if that item is out of range.

Comment: IMHO, how about just write `if col-2 > 0 && matrix[row, col-2] != 0: #branch1... else: #branch2...`?

Comment: You could put the condition in its own method so you could call something like `if outOfRange() and itemEquals(matrix[row,col-2], 0)`

Here is the accepted answer: This is as simple as 

```if col-2 &gt; 0 and matrix[row, col-2] != 0:
    # code 1
else: 
    # code 2
```

Note that ```matrix[row, col-2] != 0``` will not be executed if ```col-2 &gt; 0```is not true.

You can see this more clearly with something like:

```def raiseError():
    raise ValueError()

if False and raiseError():
    print("Won't get here")
else:
    print("No error was raised")
```



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2018:00:08/27/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python>', 'Title': "merge 'if out of range' and 'if item equals' in one condition", 'ViewCount': 39, 'id': 52041637, 'user_AboutMe': '', 'user_AccountId': 14101578.0, 'user_DisplayName': 'sovel2', 'user_Reputation': 395.0, 'user_Views': 33.0, 'user_id': 10186813.0}}