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


possible duplicate:
unexpected feature in python list of lists

so relatively new python , having trouble working 2d lists.

here's code:

data = [[none]*5]*5 data[0][0] = 'cell a1' print data 

and here output (formatted 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 every row assigned value?

this makes list 5 references same list:

data = [[none]*5]*5 

use instead creates 5 separate lists:

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

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

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -