Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2d array of zeros

Tags:

python

There is no array type in python, but to emulate it we can use lists. I want to have 2d array-like structure filled in with zeros. My question is: what is the difference, if any, in this two expressions:

zeros = [[0 for i in xrange(M)] for j in xrange(M)] 

and

zeros = [[0]*M]*N 

Will zeros be same? which one is better to use by means of speed and readability?

like image 654
yakxxx Avatar asked Oct 31 '12 12:10

yakxxx


People also ask

How do you make a 2D array zero in Python?

zeros = [ [0]*M for _ in range(N) ] # Use xrange if you're still stuck in the python2. x dark ages :). will also work and it avoids the nested list comprehension. If numpy isn't on the table, this is the form I would use.

How do you make a 2D NumPy array of zeros?

To create a multidimensional numpy array filled with zeros, we can pass a sequence of integers as the argument in zeros() function. For example, to create a 2D numpy array or matrix of 4 rows and 5 columns filled with zeros, pass (4, 5) as argument in the zeros function.


1 Answers

You should use numpy.zeros. If that isn't an option, you want the first version. In the second version, if you change one value, it will be changed elsewhere in the list -- e.g.:

>>> a = [[0]*10]*10 >>> a [[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, 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], [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, 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]] >>> a[0][0] = 1 >>> a [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]] 

This is because (as you read the expression from the inside out), you create a list of 10 zeros. You then create a list of 10 references to that initial list of 10 zeros.


Note that:

zeros = [ [0]*M for _ in range(N) ]  # Use xrange if you're still stuck in the python2.x dark ages :). 

will also work and it avoids the nested list comprehension. If numpy isn't on the table, this is the form I would use.

like image 173
mgilson Avatar answered Oct 26 '22 22:10

mgilson