Let\'s say I want to initialize a 2D Python list with all 0\'s, I\'d do something like:
test = [[0.0] * 10] * 10
Then I start modifying val
The list test
contains multiple iterations of the same list, hence a change in one (as you are making by reassigning the first element of test[0]
) is reflected in all the others. Try this instead:
[[0.0]*10 for _ in xrange(10)] # or `range` in Python 3.x
Of course, you wouldn't need to worry about this if all you had was [0.0] * 10
, since this creates a list of ints, none of which can ever mutate. Lists, on the other hand, are indeed mutable.