Creating 'board' variable


#1

In this toturial you're supposed to use the following code to make the 'board' variable:

for x in range(5):
   board.append(["O"] * 5)

However, using the following code:

board=[["O"]*5]*5

Seems to generate the same variable (when comparing both using print statements). However, when using the latter way to generate the variable, the code in part 18 gerates strange results. For example when entering 4 and 1 for the guessed row and column respectively, it returns the following:

O X O O O
O X O O O
O X O O O
O X O O O
O X O O O

When it should return:

O O O O O
O O O O O
O O O O O
O O O O O
O X O O O

What difference between the two variable formulations, causes this?


#2

Values are stored in memory.

So somewhere in memory there's some value/data that you can use, right.

In order to access that value, you need a reference to that value.

You can have multiple references to the same value, that's like writing down a street address on several slips of papers, nothing weird there.

You have five references to the same list.

This is often desirable, because it's expensive to make copies all the time, better just to say where the value is in memory.

So for example, if you do:

a = b

Then a will now refer to the very same value as b. Not a copy, the same.

There's an operator that tests if two values are the same, is. You probably won't find it very useful for your purposes, but it exists.

If you do need a copy, then you can create a copy, and and keep both references. Exactly how that's done depends on the data that is copied, but for most that'll be calling the value's type with the value as an argument, so if a is a list, that would be:

b = list(a)

Not all values can change, and so there would be little to no point in having multiple instances of them. Two examples of this are: int and str - they cannot ever be changed, only replaced. That might sound like a hindrance, but it's more of a guarantee that something won't change. If you would need to change it, then there will most likely be another data type for that purpose.

There are even a couple of values of which there only exists a single instance. True and False or examples of this, as well as None, and Python may also take the liberty of doing this with integers and strings - since they are immutable anyway.


#3

Mabye this works:

    board[guess_row][guess_col] == "X"