Initializing 2D array in Python

@Cameron is correct in suggesting that you use NumPy to deal with arrays of numerical data. And for the second part of your question, ~Niklas B. is spot on with his suggestion to use defaultdict.

What hasn’t been covered is why [[None]*6]*6 behaves strangely.

The answer is that [None]*6 creates a list with six Nones in it (like you expect), but [list]*6 does not make six independent copies of list – it makes six copies of a reference to the same list.

Idiomatic Python has a section that may explain this better: “Other languages have variables – Python has names”.

Leave a Comment