Rock-Paper-Scissors game resetting lists with history

For some reason the code below does not reset the lists storing the opponent_history and own_history. They will be emptied for the one itteration in which the if clause triggers but are reset to the orignial state in the itteration after. It works for the counter.
So any insights in this would be great since I have no clue to why it happens.

def player(prev_play, opponent_history=[], own_history = [], counter=[0]):

  if not prev_play:
    print('reset')
    del opponent_history, own_history
    own_history=[""]
    opponent_history = list()
    counter[0]=0

  opponent_history.append(prev_play)
  counter[0]+=1

  guess='R'
  
  print(counter[0])
  print(own_history[0:10])
  print(opponent_history[0:10])
  own_history.append(guess)
  return guess

Output:

playing mrugesh
reset
1
['']
['']
2
['R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R']
['R', 'P', 'P', 'S', 'R', 'R', 'P', 'P', 'P', 'P']
3
['R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R']
['R', 'P', 'P', 'S', 'R', 'R', 'P', 'P', 'P', 'P']
4
['R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R']
['R', 'P', 'P', 'S', 'R', 'R', 'P', 'P', 'P', 'P']
5
['R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R']
['R', 'P', 'P', 'S', 'R', 'R', 'P', 'P', 'P', 'P']
6
['R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R']
['R', 'P', 'P', 'S', 'R', 'R', 'P', 'P', 'P', 'P']
7
['R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R']
['R', 'P', 'P', 'S', 'R', 'R', 'P', 'P', 'P', 'P']
Final results: {'p1': 0, 'p2': 5, 'tie': 2}
Player 1 win rate: 0.0%

Internally speaking del doesn’t delete those lists, but just opponent_history and own_history names from the current scope. Actual lists would be deleted only after nothing else would point to them, but function definition does point to them. Using again those names for new lists doesn’t make them rewrite those original lists, which are still used when function is called again.

I haven’t checked this, but you might have more luck with using list clear method for this.

counter have changed directly one element, that’s a different situation.

Just to add, I think this behavior is intended to be beneficial, as it allows you to keep the history available between function calls. Instead of resetting, deleting, or clearing, just count turns and after the set number of turns pass, ignore that part of the history and just use the new history.

This probably makes more sense if you use a number, like a 1000 turns used in the tests. The first 1000 turns you can analyze for player 1’s patterns. At 1001, ignore the first 1000 and start analyzing Player 2.

It worked fine with clear.
Thank you

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.