2D list has weird behavor when trying to modify a single value

Brian picture Brian · Apr 29, 2010 · Viewed 21.3k times · Source

Possible Duplicate:
Unexpected feature in a Python list of lists

So I am relatively new to Python and I am having trouble working with 2D Lists.

Here's my code:

data = [[None]*5]*5
data[0][0] = 'Cell A1'
print data

and here is the output (formatted for readability):

[['Cell A1', None, None, None, None],
 ['Cell A1', None, None, None, None],
 ['Cell A1', None, None, None, None],
 ['Cell A1', None, None, None, None],
 ['Cell A1', None, None, None, None]]

Why does every row get assigned the value?

Answer

Mark Byers picture Mark Byers · Apr 29, 2010

This makes a list with five references to the same list:

data = [[None]*5]*5

Use something like this instead which creates five separate lists:

>>> data = [[None]*5 for _ in range(5)]

Now it does what you expect:

>>> data[0][0] = 'Cell A1'
>>> print data
[['Cell A1', None, None, None, None],
 [None, None, None, None, None],
 [None, None, None, None, None],
 [None, None, None, None, None],
 [None, None, None, None, None]]