-2

I am having troubles understanding the scope concept in Python. When I use the following code:|

x = 100

def printer(x):
    x = 25
    print(x)

printer(x) -> prints 25
print(x) -> prints 100

In the example above I understand the variable 'x' only has 25 as value in the function. When I try to do the same with a list, my output is different. See code below:

board = ['','']

def printer():
    board[0] = 'X'
    print(board)

printer() --> prints ['X', '']
print(board) --> also prints ['X', ''] || Here I was expecting to print ['','']
assangar
  • 105
  • 1
  • 8

1 Answers1

5

Only names have scopes. The x you assign before printer is a global name. The parameter x in printer is local to printer.

board is a global name. Since you never assign to board inside printer (board[0] = 'X' is not an assignment to board; it's a method call board.__setattr__(0, 'X')), it is a free variable whose value is taken from a name in an enclosing scope. The assignment mutates an existing value referenced by the global name board.

chepner
  • 497,756
  • 71
  • 530
  • 681