Python can be a little frusterating when you’re solving a problem and want to use an n-dimensional array.
First off, the Python core library lacks a generic array data structure. (It does have an array module, but it can only hold numeric types.) So, the natural option is to use a list (which is backed by an array or ListArray in the CPython and Jython implementations, respectively).
But, using a list does cause a couple of awkward moments that we need to get past. First, a list is not preallocated or initialized. To contrast, in Java, when you create an array, the array is preallocated and the values are initialized to
null. In Python, we need to manually initialize the list to the desired size. Otherwise, we will get an
IndexError if we try to make out of order assignments to the list.
In : x =  In : x Out:  In : x = 'foo' --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-3-e8db34a35d14> in <module>() ----> 1 x = 'foo' IndexError: list assignment index out of range
So, we manually initialize the list.
In : y = [None] * 10 In : y Out: [None, None, None, None, None, None, None, None, None, None] In : y = 'foo' In : y Out: [None, None, None, None, None, 'foo', None, None, None, None]
This is not too bad and seems reasonably Pythonic. But, when we go to 2-dimensions, the same strategy trips us up.
Imagine we are implementing tic-tac-toe. To create the game board, we want to use a 3 x 3 grid. So, we create and initialize a list of lists.
In : board = [[None] * 3] * 3 In : board Out: [[None, None, None], [None, None, None], [None, None, None]]
Now, let’s start the game by having X take the bottom-right postion.
In : board = 'X' In : board Out: [[None, None, 'X'], [None, None, 'X'], [None, None, 'X']]
What just happened!?! It turns out that when we created the gameboard, we created and initialized a list with 3 Nones. So far, so good. But then, we initialized our outer list with three references to the first list we created. This is not what we wanted.
So, what we should’ve said is:
In : better_board = map(lambda u: map(lambda v: None, xrange(3)), xrange(3)) In : better_board Out: [[None, None, None], [None, None, None], [None, None, None]] In : better_board = 'X' In : better_board Out: [[None, None, None], [None, None, None], [None, None, 'X']]
While we can now go about implementing tic-tac-toe, the game board creation code both smells unPythonic and seems likely to trip up future maintainers.