0

I'm still relatively new to python so try not to crucify me for any misunderstandings. I'm having trouble copying the initial value of the variable hand when it is sent to another function that updates and returns it. I get the returned value of variable(hand) as the value of the copied variable(hand2) when i want variable(hand2) to be the initial value of variable(hand)

def play_game(word_list):
   word_list = load_words
   while True:
      answer = input('\nEnter \'n\' for a new random hand, \'r\' to play the last hand, or \'e\' to exit the game: ')
      if answer == 'n':
         hand = deal_hand(HAND_SIZE)   #Here i get a randomly generated hand
         hand2 = hand    #I want to save the randomly generated hand before it's updated
         play_hand(hand,word_list)   #This function updates the hand
      elif answer == 'r':
         play_hand(hand2,word_list)  #I want to play the un-updated hand but i get the updated hand instead

Is there any way i can make variable(hand2) equal to the initial value of variable(hand)?

Thanks

Ayden Hubenak
  • 81
  • 2
  • 9

1 Answers1

2

Try using copy.deepcopy():

import copy
hand2 = copy.deepcopy(hand)

As the documentation for copy explains:

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.

ASGM
  • 11,051
  • 1
  • 32
  • 53