How do I create a multidimensional list?
Q: I created a list of lists, but when I assign to an item, the entire column is changed.
A: You probably tried to make a multidimensional array like this:
A = [[None] * 2] * 3
This looks correct if you print it:
>>> A [[None, None], [None, None], [None, None]]
But when you assign a value, it shows up in multiple places:
>>> A = 5 >>> A [[5, None], [5, None], [5, None]]
The reason is that replicating a list with * doesn’t create copies, it only creates references to the existing objects. The *3 creates a list containing 3 references to the same list of length two. Changes to one row will show in all rows, which is almost certainly not what you want.
The suggested approach is to create a list of the desired length first and then fill in each element with a newly created list:
A = [None]*3 for i in range(3): A[i] = [None] * 2
This generates a list containing 3 different lists of length two. You can also use a list comprehension:
w,h = 2,3 A = [ [None]*w for i in range(h) ]
Or, you can use an extension that provides a matrix datatype; Numeric Python is the best known.