If you have been working with python you will notice that 2d array's just don't work. This might come as a surprise since almost every other modern programming language supports 2d array's. What might even come as a bigger surprise is that python doesn't support array's at all in its language. It uses lists to support this functionality. It might look like an array but it is actually a list.

This can be shown with the following. Note the error about the list.

arr = []
arr[0] = 1

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

So once you stop thinking about trying to create and array in python (which is easy since they don't exist) and start thinking about creating a list of items things become much easier to understand why your 2d arrays of arr = [][] just doesn't work. As you have just attempts to create 2 lists and set a variable with them.

So to create a single array list is easy and we can do so using the following code.

>>> arr = range(0,5)
>>> print arr
[0, 1, 2, 3, 4]

>>> arr[0] = 1
>>> print arr
[1, 1, 2, 3, 4]

I actually find this really ugly. Since we just created a list of incremented numbers and the array still needs to be set to zero. So to create a real array preset to zero you need to use the following.

>>> arr = []
>>> for i in range(0, 5):
...  arr.append(0)
...
>>> print arr
[0, 0, 0, 0, 0]

So moving onto the 2d array and you do exactly the same thing. Except you create a list and put it in the list item. Like this

>>> arr = []
>>> for i in range(0, 5):
...  x = []
...  for j in range(0, 5):
...   x.append(0)
...  arr.append(x)
...
>>> print arr
[
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]

Now you can read / write to the items by using an array like syntax or arr[0][0] .. arr[4][4].

There is another alternative support to using 2d arrays in python by using a single list and then calculating the offsets. However for the particular problem I was trying to solve it really didn't help since python doesn't appear to
support proper for loops either!



Did You find this page useful?

Yes No



Last Modified: 17 December 2016

Releated Posts


2013-04-09 - Python - How to find out if a key exists in a dictionary
2012-08-14 - Python - while else statement
2012-06-30 - CPP - Creating A basic python wrapper
2012-02-22 - Python - 2d Arrays don't work.