Andrew Gardner
Andrew Gardner

Reputation: 21

How to write a global dictionary inside a function?

I have come across something in Python that I don't understand. I wrote some code that plays legal chess moves. The position of the pieces is remembered in a dictionary that I've called board, with an integer representing the square as a key, and the name of a piece as its value.

These values obviously change as the game progresses. I wanted to add a reset button, and originally thought I could just create a backup (e.g. backup = board), and then a function that would say board = backup. I've found this works but only if I add a second statement of the dictionary.

Here is some code that might make it clearer:

board = {11: 'white rook', 12: 'white knight', 13: 'white bishop'}
backup = board
# if I comment out this next line the code doesn't work 
board = {11: 'white rook', 12: 'white knight', 13: 'white bishop'}

def move_knight():
    board[12] = 'empty'  # as the knight moves away
    
def reset():
    global board
    board = backup
    print("board in reset function =", board)

move_knight()
print("board after knight's move =", board)
reset()
print("board after reset =", board)

In a sense I have solved my problem but would like to understand why.

Upvotes: 0

Views: 84

Answers (1)

tbjorch
tbjorch

Reputation: 1748

Explaining problem

You are just creating a new list and change the reference of 'board' variable to a new list.

first = [1, 2, 3]  # Creating a list and variable 'first' refers to the list
second = first     # Creating variable 'second' and refer to the same list as first
first = [3, 4, 5]  # Create a new list and let variable 'first' refer to the new list

if you try this you would see that the variables are pointing on the same list:

first = [1, 2, 3]
second = first
print(first, second) # outputs [1, 2, 3] [1, 2, 3]
first[0] = 5 # <--- updating via variable 'first'
print(first, second) # outputs [5, 2, 3] [5, 2, 3]

How to create a copy

If you use the copy method you will see that you are indeed creating a copy of the list into the new variable and not only just referring to the same list.

first = [1, 2, 3]
second = first.copy()
print(first, second) # outputs [1, 2, 3] [1, 2, 3]
first[0] = 5
print(first, second) # outputs [5, 2, 3] [1, 2, 3]

Upvotes: 1

Related Questions