Kobi
Kobi

Reputation: 1495

How do I initialize a one-dimensional array of two-dimensional elements in Python?

I want to initialize an array that has X two-dimensional elements. For example, if X = 3, I want it to be [[0,0], [0,0], [0,0]]. I know that [0]*3 gives [0, 0, 0], but how do I do this for two-dimensional elements?

Upvotes: 2

Views: 1646

Answers (4)

ftw
ftw

Reputation: 385

Using the construct

[[0,0]]*3

works just fine and returns the following:

[[0, 0], [0, 0], [0, 0]]

Upvotes: 0

Óscar López
Óscar López

Reputation: 235984

Try this:

m = [[0] * 2 for _ in xrange(3)]

In the above code, think of the 3 as the number of rows in a matrix, and the 2 as the number of columns. The 0 is the value you want to use for initializing the elements. Bear in mind this: if you're using Python 3, use range instead of xrange.

For a more general solution, use this function:

def create_matrix(m, n, initial=0):
    return [[initial] * n for _ in xrange(m)]

For the particular case of the question:

m = create_matrix(3, 2)
print m
> [[0, 0], [0, 0], [0, 0]]

Alternatively, and if you don't mind using numpy, you can use the numpy.zeros() function as shown in Mellkor's answer.

Upvotes: 6

Arjun
Arjun

Reputation: 1279

I guess numpy.zeros is useful for such. Say,

x=4

numpy.zeros((x,x))

will give you:

array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]])

Upvotes: 3

AI Generated Response
AI Generated Response

Reputation: 8837

I believe that it's [[0,0],]*3

Upvotes: 0

Related Questions