Python: Replacing an element in a list of lists (#2)

reek picture reek · Oct 4, 2010 · Viewed 7.3k times · Source

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

Answer

Tony Veijalainen picture Tony Veijalainen · Oct 4, 2010

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)