Multidimensional list (array) in python

By: Python Documentation Team Viewed: 153221 times  Printer Friendly Format    

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[0][0] = 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.

Most Viewed Articles (in Python )

Latest Articles (in Python)

Comment on this tutorial