1

I am trying to write a function which enables a move 1 unit to the left (in the x-axis) in a grid. It should only work if there is a valid coordinate to the left, and if not (i.e. the start point is on the edge of the grid), the function should return None. Here is my attempt:

def left_move(point):
    try: 
        LEFT = grid[point[1]][point[0]-1]
    except IndexError: 
        return None
    if LEFT == '.':
        change = [-1,0]
        for idx, amount in enumerate(change):
            point[idx]+=amount
        return point
    return None

Say the starting point is [0,3] and therefore on the edge of the grid and I only run the top part of the code:

def left_move(point):
    try: 
        LEFT = grid[point[1]][point[0]-1]
    except IndexError: 
        return None

It returns None as expected. But if the whole block is executed it returns [-1,3] which is outside of the grid and shouldn't be allowed by the try-except . Why is this? And how can it be corrected?

2 Answers 2

2

This is because Python's interpretation of -1 in array indexing is the last element of the array. -1 is a legal way of referencing array elements and thus will not trigger an IndexError exception.

>>> a = [0,1,2]
>>> print a[-1]
2

You would need to manually check if the value you are given resolves to -1 and then handle that accordingly.

Sign up to request clarification or add additional context in comments.

Comments

2

Here, you need to place the rest of the code inside the try statement. Otherwise, it will try, fail, and then run the rest of the code.

def left_move(point):
    if point[0]-1 != -1: 
        LEFT = grid[point[1]][point[0]-1]
        if LEFT == '.':
            change = [-1,0]
            for idx, amount in enumerate(change):
                point[idx]+=amount
            return point
        return None
    else: 
        return None

3 Comments

The code yields the same result whether the if statement is within the try block or not. If there is an exception then the function will return None and not execute the rest of the block.
ahh yes now I see, you need to refer to Jokab's answer, but its because -1 is a valid index in python. I replaced the try/except with a simple if statement, it should do the same. The reason the code was working when you only had the try/except was because the code would finish with no problem, and not find a return statement so simply returned None by default, or at least thats my guess. @ggordon
Yes replacing the try-except with if is a good idea, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.