0

So i have a list for tic tac toe and I reacive the board like this

board=[' ', 'X', 'O', ' ', ' ', 'X', ' ', 'O', ' ', ' ']

I would like to make to two variable for something in my mind the first variable is the O_variable wich will contain all the o's in the list and replace them with 1 and should be like this [0,0,1,0,0,0,0,1,0,0]and the same for the x's [0,1,0,0,0,1,0,0,0,0] so try the following code

Bo_variable=O_variable=x_variable=[0,0,0,0,0,0,0,0,0,0]
for i in range(len(board)):
    if board[i]=='O':
        O_variable[i]=1
    if boardt[i]=='X':
        x_variable[i]=1

but the outcome for both variable O_variable and x_variable is the same

[0,1,1,0,0,1,0,1,0,0]

what causes this? Note : I don't to encode the list from the first i receive it like this

noob
  • 672
  • 10
  • 28

3 Answers3

2

Both O_variable and x_variabl reference to the same array, therefore changed altogether.

Define them in separate lines.

O_variable = [0,0,0,0,0,0,0,0,0,0]
x_variabl  = [0,0,0,0,0,0,0,0,0,0]

As @yatu commented, this can be converted to the more resilient code:

BOARD_SIZE = 10
# Create a zeros array of size `BOARD_SIZE`
O_variable = [0] * BOARD_SIZE
# Copy `O_variable` zeroes array
x_variable = O_variable[:]
Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22
  • You might want to define those lists with somethings like `O_variable = [0 for _ in range(10)]; x_variable = O_variable[:]` instead @RAbeeq `O_variable[:]` copies the first list – yatu Aug 31 '20 at 07:24
  • Of course, that would be more resilient, and better. Just wanted to pass the point to the OP, anyway I'll update. Thank you @yatu – Aviv Yaniv Aug 31 '20 at 07:25
  • No worries @AvivYaniv :) Important here it for OP to understand the concept of a *copy* – yatu Aug 31 '20 at 07:26
  • Indeed @yatu! Updated :) – Aviv Yaniv Aug 31 '20 at 07:29
1

This declaration means both your O_variable and x_variable are pointing to the same list.

Bo_variable=O_variable=x_variable=[0,0,0,0,0,0,0,0,0,0] 

hence when you call O_variable[i]=1 and x_variable[i]=1 they're both modifying the same list. You need to separate O_variable and x_variable

O_variable=[0,0,0,0,0,0,0,0,0,0]
x_variable=[0,0,0,0,0,0,0,0,0,0]

If you want a Bo_varaible list you can combine then after they are finished through the loop via

bo_variable = [0,0,0,0,0,0,0,0,0,0]
for i in range(len(bo_variable)):
    if O_variable[i] == 1 or x_variable[i]==1:
        bo_variable[i] =1
Jeff
  • 610
  • 4
  • 12
1

Your problem is because of the first line. You initialized the 2 variables in a wrong way.

If you O_variable=x_variable=[0,0,0,0,0,0,0,0,0,0], then the 2 variables uses a same memory, so either variable's change affects the other.

You should initialize the 2 variables separately like this.

x_variable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
O_variable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Ahmed Mamdouh
  • 696
  • 5
  • 12