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]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0] = 1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 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 this will also work and it avoids the nested list comprehension:

zeros = [ [0]*M for _ in range(N) ]

If numpy isn't on the table, this is the form I would use.

(Use xrange if you're still stuck in the python2.x dark ages :).)

Answer from mgilson on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-create-an-array-of-zeros-in-python
How to create an array of zeros in Python? - GeeksforGeeks
July 23, 2025 - Explanation: This code creates ... loop runs 5 times for columns, producing a matrix of zeros. bytearray creates a mutable array of bytes initialized to zero....
Discussions

python - Create arbitrary multidimensional zeros array - Stack Overflow
pythonjavascriptc#reactjsjavaandroidhtmlflutterc++node.jstypescriptcssrphpangularnext.jsspring-bootmachine-learningsqlexceliosazuredocker ... Next You’ll be prompted to create an account to view your personalized homepage. Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Save this question. Show activity on this post. I need to make a multidimensional array of zeros... More on stackoverflow.com
🌐 stackoverflow.com
python - How to define a two-dimensional array? - Stack Overflow
I want to define a two-dimensional array without an initialized length like this: Matrix = [][] But this gives an error: IndexError: list index out of range More on stackoverflow.com
🌐 stackoverflow.com
Populate numpy matrix with zeros and ones
You can use ravel and then do it linearly: >>> grid = np.zeros((4,4), int) >>> choices = np.random.choice(grid.size, 6, replace=False) >>> grid.ravel()[choices] = 1 >>> grid array([[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 0, 0], [1, 0, 0, 0]]) This random picks 6 indices from the flattened version of grid, then it flattens it without making a copy and sets each of those 6 elements to 1. Since it doesn't make a copy, the original, unflattened version also gets the 1 values (since it is all the same array internally). You can also use unravel_index to convert linear indexes to 2D indexes, but in this case I think that is longer and less clear. More on reddit.com
🌐 r/learnpython
5
4
October 17, 2017
How to mix strings and floats in a NumPy array?

I'd consider a pandas DataFrame instead - the actual data is stored as a numpy array and so supports everything it needs to, and the headers are separate so you don't need to do awkward slicing when working on the whole data set. You can also then index rows and columns by their index. And it supports going to and from CSVs easily.

As an aside, the way to get arrays to accept mixed types is

np.array([1, 'a'], dtype=object)

but obviously you lose practically all of the benefits of using numpy in the first place.

More on reddit.com
🌐 r/learnpython
8
6
January 26, 2015
🌐
Sentry
sentry.io › sentry answers › python › define a two-dimensional array in python
Python Define a Two-Dimensional Array or Matrix | Sentry
September 23, 2026 - Create a 2D array in Python using numpy.zeros for matrix operations, or a nested list comprehension if you want to avoid the numpy dependency
🌐
GeeksforGeeks
geeksforgeeks.org › python › create-a-numpy-array-filled-with-all-zeros-python
Create a Numpy array filled with all zeros - Python - GeeksforGeeks
September 19, 2025 - By default, the data type of the array is float, so the zeros are represented as 0.0. ... This code creates a 2D array of zeros with 3 rows and 4 columns using np.zeros().
🌐
Codecademy
codecademy.com › docs › python:numpy › built-in functions › .zeros()
Python:NumPy | Built-in Functions | .zeros() | Codecademy
June 23, 2025 - This example creates a 1D array of five zeros and a 2D array of zeros with shape (3, 2) and integer data type using NumPy’s .zeros() function:
🌐
iO Flood
ioflood.com › blog › np-zeros
NP.Zeroes | Using Zeros() In Numpy
January 31, 2024 - To create a 2D array, we pass a tuple to the np.zeros function, specifying the number of rows and columns.
Find elsewhere
🌐
Finxter
blog.finxter.com › home › learn python blog › how to create a two dimensional array in python?
How To Create a Two Dimensional Array in Python? - Be on the Right Side of Change
June 11, 2022 - To create/initialize an empty 2D array loaded with zeros, for every occurrence of a row, we fill all the column elements and append that to the row. Approach: We first create a sub-list representing all the column values and append it to the ...
🌐
W3docs
w3docs.com › home › code snippets › python › how to initialize a two-dimensional array in python?
How to initialize a two-dimensional array in Python? | W3docs
You can use the built-in list function to create a 2D array (also known as a list of lists) in Python. Here is an example of how to create a 2D array with 3 rows and 4 columns, filled with zeroes:
🌐
Vultr Docs
docs.vultr.com › python › third party › numpy › zeros()
Python Numpy zeros() - Create Zero Array | Vultr Docs
January 1, 2025 - In this article, you will learn how to deploy the numpy.zeros() function effectively in generating zero-filled arrays in Python. Explore how to create arrays of different shapes and dimensions and understand the use of data type specifications ...
🌐
GeeksforGeeks
geeksforgeeks.org › numpy › numpy-zeros-python
numpy.zeros() in Python - GeeksforGeeks
June 15, 2026 - Explanation: np.zeros((3, 4)) creates a 2D array with 3 rows and 4 columns filled with 0.
🌐
w3resource
w3resource.com › numpy › array-creation › zeros.php
NumPy: numpy.zeros() function - w3resource
April 21, 2026 - In this example, a tuple (3, 2) defines the shape of the array, and np.zeros() creates a 2D array filled with zeros.
🌐
Snakify
snakify.org › two-dimensional lists (arrays)
Two-dimensional lists (arrays) - Learn Python 3 - Snakify
But the easiest way is to use generator, creating a list of n elements, each of which is a list of m zeros: ... In this case each element is created independently from the others.
🌐
MLJAR
mljar.com › answers › define-two-dimensional-array-python
Define two-dimensional array in Python
array[2][2] = 5 # valid array[7][2] = 3 # error · This way is much easier. You can use zeros function from numpy to create 2D array with all values set to zero: import numpy array = numpy.zeros((4,4)) REMEMBER Even though the second version is easier, the first one is better for this operation ...
🌐
Cf
physics-python.astro.cf.ac.uk › Week6
PX1224 -Week6: Two Dimensional Arrays
Full colour images actually store 3 values, "redness", "blueness" and "greeness" for each value, so can be thought of as three 2D arrays. Alternatively, a 3D array, eg 1200 elements by 800 elements (ie a screen resolution of 1200x800) by 3 elements can represent a full colour image on the screen. To generate an image like this, we first want to create x and y arrays using mgrid(), then calculate a "height" value, z, at each point in x and y. Finally, we plot a contour plot using the values of z to give the colours. The code to do this is given below · Python can show such images.
🌐
Python Guides
pythonguides.com › create-an-array-of-zeros-in-python
How To Create An Array Of Zeros In Python?
July 7, 2026 - How does this code work? You pass (12, 3) as the shape and np.int64 as the dtype to np.zeros(), which creates a 2D array of zeros where every element is a 64‑bit integer.
🌐
Python Examples
pythonexamples.org › python-numpy-zeros
Create Array with Zeros in NumPy - Examples
To create a numpy array with all zeros, of specific dimensions or shape, use numpy.zeros() function.
Top answer
1 of 7
1263

You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this "list comprehension".

# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5
Matrix = [[0 for x in range(w)] for y in range(h)] 

#You can now add items to the list:

Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range... 
Matrix[0][6] = 3 # valid

Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".

print Matrix[0][0] # prints 1
x, y = 0, 6 
print Matrix[x][y] # prints 3; be careful with indexing! 

Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.

2 of 7
487

If you really want a matrix, you might be better off using numpy. Matrix operations in numpy most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:

>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 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.]])

Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):

numpy.arange(25).reshape((5, 5))         # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5))   # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5))    # pass a Python list and reshape
numpy.empty((5, 5))                      # allocate, but don't initialize
numpy.ones((5, 5))                       # initialize with ones

numpy provides a matrix type as well, but it is no longer recommended for any use, and may be removed from numpy in the future.

🌐
GeeksforGeeks
geeksforgeeks.org › numpy › how-to-create-array-of-zeros-using-numpy-in-python
How to Create Array of zeros using Numpy in Python - GeeksforGeeks
July 23, 2025 - Verify the Output: Print or inspect the array to ensure it meets your requirements. ... The numpy.zeros() function allows specifying the data type of the elements using the dtype parameter.
🌐
AskPython
askpython.com › python-modules › numpy › numpy-zeros-method-in-python
NumPy zeros() Method in Python - AskPython
March 12, 2020 - import numpy as np int_array = np.zeros(4, dtype=int) #data type set as int print("Array: ",int_array) #the final int array print("Datatype: ", int_array.dtype) # the data types ...