How to create nested lists in python?

Jader Dias picture Jader Dias · Jan 31, 2010 · Viewed 14.8k times · Source

I know you can create easily nested lists in python like this:

[[1,2],[3,4]]

But how to create a 3x3x3 matrix of zeroes?

[[[0] * 3 for i in range(0, 3)] for j in range (0,3)]

or

[[[0]*3]*3]*3

Doesn't seem right. There is no way to create it just passing a list of dimensions to a method? Ex:

CreateArray([3,3,3])

Answer

user44484 picture user44484 · Jan 31, 2010

In case a matrix is actually what you are looking for, consider the numpy package.

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html#numpy.zeros

This will give you a 3x3x3 array of zeros:

numpy.zeros((3,3,3)) 

You also benefit from the convenience features of a module built for scientific computing.