Search code examples
pythonscopenested-function

Python Slice operation causing UnboundLocalError: local variable referenced before assignment


If I use curr = curr[:-1] to remove the last element, it gives the error: UnboundLocalError: local variable 'curr' referenced before assignment on line 13 which is if (len(curr) >= len(word)):

while if I do curr.pop() to remove the last element, it works. Curious to know why. I am using Python 3

class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
    ROWS, COLS = len(board), len(board[0])
    
    curr = []
    visited = set()
    
    def dfs(i, j):
        if (i, j) in visited:
            return False
        if (i < 0 or j < 0 or i >= ROWS or j >= COLS):
            return False
        if (len(curr) >= len(word)):
            return False
        
        visited.add((i,j))
        curr.append(board[i][j])
        result = ("".join(curr) == word) or dfs(i + 1, j) or \
                dfs(i, j + 1) or \
                dfs(i - 1, j) or \
                dfs(i, j - 1)
        
        curr = curr[:-1]       #here
        visited.remove((i,j))
        
        return result
    
    for r in range(ROWS):
        for c in range(COLS):
            if dfs(r, c):
                return True
    
    return False
        
        

Error Trace:

UnboundLocalError: local variable 'curr' referenced before assignment
  if (len(curr) >= len(word)):
Line 13 in dfs (Solution.py)
  if dfs(r, c):
Line 30 in exist (Solution.py)
  ret = Solution().exist(param_1, param_2)
Line 58 in _driver (Solution.py)
  _driver()
Line 69 in <module> (Solution.py)

Solution

  • As pointed out by Michael,

    If an assignment to a variable appears anywhere in a function, the variable is seen as local if not explicitly declared as "global" or "nonlocal"