1
a1 = '   '
a2 = '   '
a3 = '   '
b1 = '   '
b2 = '   '
b3 = '   '
c1 = '   '
c2 = '   '
c3 = '   '
boardspace = [[a1,a2,a3],[b1,b2,b3],[c1,c2,c3],[a1,b1,c1],[a2,b2,c2],[a3,b3,c3],[a1,b2,c3],[a3,b2,c1]]

while x != 'a'
    a1 = '0'
    a2 = '0'
    a3 = '0'
    for a in baordspace:
        if a[0]==a[1]==a[2]!= "  "
           x ='a'

As you can see the list will always print "" "" ""

a1 a2 a3 will never be '0' in the for loop, why is that?

But if you print a1 it is '0' , however [a1,a2,a3] is "" "" ""

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Malfoy Drako
  • 23
  • 1
  • 7

1 Answers1

2

I think you're misunderstanding the meaning of a variable.

When you create your list "boardspace", you are creating it with the values that a1 et al contain at that time. Then you reassign the variable a1 et al to a different value.

The list does not contain a1 or any of the other variables, but lists of strings. That's all.

Edit:

Say you have something like this:

a = 1
b = 2
arr = [[a, b], [b, a]]

And you want a change to a to be reflected in both sub lists in arr, then you'll need to do one of two things:

  1. Convert these variables to objects
  2. Store indexes in arr to a separate list (not as nice)

There are reasons for both, but since you'll likely want to do #1, here's an example:

class Tile:
    def __init__(self, val):
        self.val = val

    def __repr__(self):
        return self.val

    def __str__(self):
        return self.val

a = Tile('  ')
b = Tile('  ')

arr = [[a, b], [b, a]]

print arr # [[  ,   ], [  ,   ]]

a.val = '0'

print arr # [[0,   ], [  , 0]]

I've defined a class with some magic functions:

  • __init__- Constructor
  • __str__- str(obj) is equivalent to obj.__str__()
  • __repr__- Outputs a representation of the object. In this case, we only have one value, so val is a sufficient representation. It also makes print arr work. See the last post here for more info

The change here is that we've created an object. Python passes everything by value, so when it passes the objects we created to the array, the reference is copied, but the underlying object is the same.

This means that any change to any of these objects will behave as you anticipated in your question.

beatgammit
  • 19,817
  • 19
  • 86
  • 129