2

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?

3
  • 1
    Most of the time in Python, if you are thinking in terms of "initializing" a container to a bunch of 0s, you are doing it wrong. Commented Apr 11, 2012 at 4:09
  • Well I'm practicing for Google Code Jam and I have to read in a stream of numbers for example 2, 3, 1, 4, 5, 2 and turn it into [[2,3], [1,4], [5,2]]. What else would you suggest? Commented Apr 11, 2012 at 4:31
  • 1
    I would suggest appending the numbers to empty lists as they are received. Commented Apr 11, 2012 at 4:50

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.]])

Comments

0

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

3 Comments

The way it works is it adds the stuff inside the list as a list to itself multiple times, essentially being [[0,0],]+[[0,0],]+[[0,0],]
This makes a list containing three references to the same list, so it's not the same as [[0,0],]+[[0,0],]+[[0,0],]. Try changing one of the elements, and you'll see all three sublists change.
This solution is broken. It creates 3 copies of the same list of two elements, when you try to modify one, all the others will get modified too.
0

Using the construct

[[0,0]]*3

works just fine and returns the following:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.