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.

Answer from Manny D on Stack Overflow
Top answer
1 of 16
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 16
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.

🌐
DaniWeb
daniweb.com › programming › software-development › threads › 160559 › empty-2d-array
python - Empty 2D Array [SOLVED] | DaniWeb
December 3, 2008 - For heavy numeric work, prefer NumPy arrays for performance and vectorization; initialize once you know dimensions: arr = numpy.zeros((rows, cols)) (NumPy zeros). More on the aliasing gotcha: Python FAQ: multidimensional lists. defaultdict docs: collections.defaultdict. hoe to write a generic code for creating a empty 2D array and dynamically insert values in it.
Discussions

Python create empty 2-dimensional array - Stack Overflow
I am trying to generate an empty 2-dimensional array by using to for-loops. More on stackoverflow.com
🌐 stackoverflow.com
How to initialize a two-dimensional array (list of lists, if not using NumPy) in Python? - Stack Overflow
I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this: def initialize_twodlist(foo): twod_list ... More on stackoverflow.com
🌐 stackoverflow.com
How can I create a truly empty numpy array which can be merged onto (by a recursive function)?
I can't say I fully followed your problem statement, but you can create an array with a total size of zero if any of the dimensions has size zero: a = np.empty((0, 3)) # Doesn't really matter if you use `empty`, `zeros` or `ones` here Zero-size arrays are the neutral element wrt. concatenation along their zero-size dimension (if that's what you mean by "merging"): b = np.random.uniform(size=(20, 3)) c = np.concatenate([a, b], 0) (c == b).all() # True More on reddit.com
🌐 r/learnpython
2
2
September 21, 2023
how would you instantiate a two-dimensional array in the constructor?
I assume by 2d array you mean nested lists. Also you shouldn't use mutable types as default argument. I would do something like this: class MyClass: def __init__(self, matrix=None): self.matrix = matrix or [['some', 'default'], ['data', ['...']] More on reddit.com
🌐 r/learnpython
4
1
November 21, 2021
🌐
Sentry
sentry.io › sentry answers › python › define a two-dimensional array in python
Define a two-dimensional array in Python | Sentry
The following code will create ... this operation. To create a 2D array without using numpy, we can initialize a list of lists using a list comprehension....
🌐
Python Guides
pythonguides.com › create-an-empty-array-in-python
Ways to Initialize an Empty Python Array
January 12, 2026 - If I am processing a list of zip codes from the United States Census Bureau, I use the Python array module to save memory. import array # Creating an empty Python array of integers ('i' represents signed integers) # This is useful for memory-efficient storage of USA Zip Codes zip_codes = array.array('i') print(f"Empty Python Array: {zip_codes}") # Adding a Beverly Hills zip code zip_codes.append(90210) print(f"Updated Python Array: {zip_codes}")
🌐
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 - Here’s a diagrammatic representation ... If you want to create an empty 2D array without using any external libraries, you can use nested lists....
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-using-2d-arrays-lists-the-right-way
Using 2D arrays/lists in Python - GeeksforGeeks
Python creates only one inner list and one 0 object, not separate copies. This shared reference behavior is known as shallow copying (aliasing). If we assign the 0th index to another integer say 1, then a new integer object is created with the value of 1 and then the 0th index now points to this new int object as shown below · Similarly, when we create a 2d array as "arr = [[0]*cols]*rows" we are essentially extending the above analogy.
Published: December 20, 2025
🌐
Quora
quora.com › How-do-you-create-an-empty-multidimensional-array-in-Python
How to create an empty multidimensional array in Python - Quora
Answer (1 of 5): You can’t - a multidimensional list (not array) in Python is a list of lists. if the top level list is empty then it isn’t multidimensional - it is an empty list. if the list on the next level down are empty then you have a list which is N by zero - hardly multi-dimensional.
Find elsewhere
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.empty.html
numpy.empty — NumPy v2.2 Manual
In this case, it ensures the creation of an array object compatible with that passed in via this argument. New in version 1.20.0. ... Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None. ... Return an empty array with shape and type of input.
🌐
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 ...
🌐
Statistics Globe
statisticsglobe.com › home › python programming language for statistics & data science › create empty 2d list in python (2 examples)
Create Empty 2D List in Python (2 Examples) | Zero Elements
March 31, 2023 - With the second loop, we created columns of “None” values, which corresponded to the number of columns we initialized, and appended that to the rows using the append() method. The rows were then appended to the empty 2D list called “my_list”. Here, we will make use of list comprehension method to generate an empty 2D list in Python:
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.empty.html
numpy.empty — NumPy v2.5 Manual
In this case, it ensures the creation of an array object compatible with that passed in via this argument. New in version 1.20.0. ... Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None. ... Return an empty array with shape and type of input.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › numpy empty array with examples
NumPy Empty Array With Examples - Spark By {Examples}
March 27, 2024 - NumPy empty() array function in Python is used to create a new array of given shapes and types, without initializing entries. This function takes three
🌐
GeeksforGeeks
geeksforgeeks.org › python-using-2d-arrays-lists-the-right-way
Python | Using 2D arrays/lists the right way - GeeksforGeeks
The code then shows another approach using a nested list comprehension to create the 2D array arr. This method avoids aliasing by creating a new list for each row, resulting in a proper 2D array. ... # Python 3 program to demonstrate working # of method 1 and method 2.
Published: June 20, 2024
🌐
Quora
quora.com › How-do-you-create-an-empty-2D-list-in-Python
How to create an empty 2D list in Python - Quora
Answer (1 of 10): C̲r̲e̲a̲t̲i̲n̲g̲ ̲a̲n̲ e̲m̲p̲t̲y̲ ̲2̲D̲ ̲li̲s̲t̲ ̲i̲n̲ ̲P̲y̲t̲h̲o̲n̲ ̲i̲s̲ ̲s̲t̲r̲a̲i̲g̲h̲t̲f̲o̲r̲w̲ar̲d̲ ̲,̲ ̲b̲u̲t̲ ̲u̲n̲d̲e̲r̲s̲t̲a̲n̲di̲n̲g̲ ̲t̲h̲e̲ ̲n̲u̲a̲n̲c̲e̲s̲ ̲e̲ns̲u̲r̲e̲s̲ ...
🌐
Python Forum
python-forum.io › thread-1818.html
Creating 2D array without Numpy
I want to create a 2D array and assign one particular element. The second way below works. But the first way doesn't. I am curious to know why the first way does not work. Is there any way to create a zero 2D array without numpy and without loop? ...
🌐
Dot Net Perls
dotnetperls.com › 2d-python
Python - 2D List Examples - Dot Net Perls
Python supports a special "array" from the array module. An integer array is more compact in memory than an integer list. We can create a flattened 2D array.
🌐
Python Guides
pythonguides.com › python-numpy-empty-array
Create An Empty Array Using NumPy In Python
May 16, 2025 - NumPy’s empty() function in Python is the fastest way to create an empty array as it allocates memory without initializing the values. import numpy as np # Create a 1D empty array of size 5 empty_array_1d = np.empty(5) print("1D Empty Array:") print(empty_array_1d) # Create a 2D empty array ...
🌐
Javatpoint
javatpoint.com › python-2d-array
Python 2D array - Javatpoint
January 10, 2021 - Python 2D array with python, tutorial, tkinter, button, overview, entry, checkbutton, canvas, frame, environment set-up, first python program, operators, etc.