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

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]]

Leave a Comment