-1

I have a python script were I was experimenting with minmax AI. And so tried to make a tic tac toe game.

I had a self calling function to calculate the values and it used a variable called alist(not the one below) which would be given to it by the function before. it would then save it as new list and modify it.

This worked but when it came to back-tracking and viewing all the other possibilities the original alist variable had been changed by the function following it e.g.

import sys
sys.setrecursionlimit(1000000)
def somefunction(alist):
    newlist = alist
    newlist[0][0] = newlist[0][0] + 1
    if newlist[0][0] < 10:
        somefunction(newlist)
    print(newlist)
thelist = [[0, 0], [0, 0]]
somefunction(thelist)

it may be that this is difficult to solve but if someone could help me it would be greatly appreciated

Spitfire972
  • 33
  • 2
  • 7

2 Answers2

1

newlist = alist does not make a copy of the list. You just have two variable names for the same list.

There are several ways to actually copy a list. I usually do this:

newlist = alist[:]

On the other hand, that will make a new list with the same elements. To make a deep copy of the list:

import copy
newlist = copy.deepcopy(alist)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
zvone
  • 18,045
  • 3
  • 49
  • 77
0

You probably want to deepcopy your list, as it contains other lists:

from copy import deepcopy

And then change:

newlist = alist

to:

newlist = deepcopy(alist)
iz_
  • 15,923
  • 3
  • 25
  • 40