views:

60

answers:

1

A previous question with the same title as mine has been posted, with (I think) the same question, but had other problems in the code. I was not able to determine if that case was identical to mine or not.

Anyway, I want to replace an element within a list in a list. Code:

myNestedList = [[0,0]]*4 # [[0, 0], [0, 0], [0, 0], [0, 0]]
myNestedList[1][1] = 5

I now expect:

[[0, 0], [0, 5], [0, 0], [0, 0]]

But I get:

[[0, 5], [0, 5], [0, 5], [0, 5]]

Why?

This is replicated in the command line. Python 3.1.2 (r312:79147, Apr 15 2010, 15:35:48) [GCC 4.4.3] on linux2

+8  A: 

You are having four references to same object by * 4, use instead list comprehension with range for counting:

my_nested_list = [[0,0] for count in range(4)]
my_nested_list[1][1] = 5
print(my_nested_list)

To explain little more concretely the problem:

yourNestedList = [[0,0]]*4
yourNestedList[1][1] = 5
print('Original wrong: %s' % yourNestedList)

my_nested_list = [[0,0] for count in range(4)]
my_nested_list[1][1] = 5
print('Corrected: %s' % my_nested_list)

# your nested list is actually like this
one_list = [0,0]
your_nested_list = [ one_list for count in range(4) ]
one_list[1] = 5
print('Another way same: %s' % your_nested_list)
Tony Veijalainen
+1. This can be bewildering at first. The explanation and solution are both good.
Manoj Govindan
I have been hit by this problem myself, of course ;)
Tony Veijalainen
Ahh, tricky for a beginner. Thanks a lot for the help!
Richard_humlab