Game Development Reference
In-Depth Information
10 - Tic Tac Toe
>>> spam = [0, 1, 2, 3, 4, 5]
>>> cheese = spam
>>> cheese[1] = 'Hello!'
>>> spam
[0, 'Hello!', 2, 3, 4, 5]
>>> cheese
[0, 'Hello!', 2, 3, 4, 5]
Notice that the line
cheese = spam
copies the
list reference
in
spam
to
cheese
,
instead of copying the
list value
itself. This is because the value stored in the
spam
variable is a list
reference
, and not the list
value
itself. This means that the values stored in
both
spam
and
cheese
refer to the same list. There is only one list because the list was
not copied, the reference to the list was copied. So when you modify
cheese
in the
cheese[1] = 'Hello!'
line, you are modifying the same list that
spam
refers to.
This is why
spam
seems to have the same list value that
cheese
does.
Remember when you first learned about variables, I said that variables were like boxes
that contain values. List variables don't actually contain lists at all, they contain references
to lists. Here are some pictures that explain what happens in the code you just typed in:
Figure 10-5: Variables do no store lists, but rather references to lists.
On the first line, the actual list is not contained in the
spam
variable but a reference to
the list. The list itself is not stored in any variable.