Lists & two dimensions
Jim Jinkins
j-jinkins at usa.net
Sun Jul 21 10:28:33 EDT 2002
Pichai Asokan wrote:
>I am a trainer and in a training session a participant came up with a
>problem that stumped me:
>
>Here is the code snippet that isolates what I want:
>--------------------
>board = [[-1] * 3 ]*3
>print board
>board[1][2] = 'x'
>print board
>--------------------
>Output
>-----------------------
>[ [-1, -1, -1 ], [-1, -1, -1 ], [-1, -1, -1 ] ]
>[ [-1, -1, 'x'], [-1, -1, 'x'], [-1, -1, 'x'] ]
>-----------------------
>
>I thought
>board = [[-1] * 3 ]*3
>should give me a list of 9 elements;
>but ...
>
>What is going on?
>Where can we read more to understand what is goingg on?
>
>P Asokan
>
>
Cut and paste the code below. Then play with it. I learned a few
things building it.
Jim Jinkins
#
-------------------------------------------------------------------------------
# a = [[0] * 3] * 3 is equivalent to a = b * 3
# where b is [0] * 3
# which is equivalent to this code:
b = [] # Create a new empty list
for i in range(3):
print "b = %s i = %d" % (b, i)
b.append(0)
print "b = %s final" % b
# Uncomment these lines to make what is happening easier to see.
# b[2] = -1
# print "b[2] = -1 makes b = %s" % b
a = []
for i in range(3):
print "a = %s i = %d" % (a, i)
a.append(b)
print "a = %s final" % a
a[0][0] = 1
print "Executine a[0][0] = 1 makes a = %s" % a
# List a contains 3 references to a list of 3 elements.
# Changing that list changes what you see
# through all 3 references (all three row elements.)
# Now create a from 3 separate copies of b
a = []
for i in range(3):
print "a = %s i = %d" % (a, i)
b = [] # Create a new empty list
for i in range(3):
print "b = %s i = %d" % (b, i)
b.append(0)
# Uncomment these lines to make what is happening
# easier to see.
# b[2] = -(i + 1)
print "b = %s final" % b
a.append(b)
print "a = %s final" % a
a[0][0] = 1
print "Executine a[0][0] = 1 makes a = %s" % a
# List a contains references to 3 separate lists.
# Changing any one of them does not change the
# others
# Now create a with a list comprehension
a = [[0] * 3 for i in range(3)]
a[0][0] = 1
print "Executine a[0][0] = 1 makes a = %s" % a
# The list comprehension created 3 separate instances
# of its outer expression, [0] * 3.
# ---------------------------------------------------------------------
More information about the Python-list
mailing list