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.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-using-2d-arrays-lists-the-right-way
Using 2D arrays/lists in Python - GeeksforGeeks
The code below, compares two ways of initializing a 2D list in Python. Using list multiplication ([[0]*cols]*rows) creates multiple references to the same inner list, causing aliasing where changes affect all rows. Using a nested list comprehension creates a separate list for each row, avoiding aliasing and correctly forming a 2D array.
Published: December 20, 2025
🌐
Python.org
discuss.python.org › python help
Need help with a two-dimensional array - Python Help - Discussions on Python.org
June 3, 2022 - Hello there! I’m an experienced coder who’s just getting into Python for the first time. I know several versions of BASIC, Pascal, C, C++, C#, PHP, MySQL… and so on. Here’s what I have: 1 2 3 4 5 6 7 8 A X X X X X X X X B X X X X X T X X C X X X X X X X X D X X X X X X X X E X X X X X X X X F X X X X X X X X G X X X X X X X X H X X X X X X X X This is a simple two-dimensional array.
🌐
NumPy
numpy.org › doc › 2.5 › reference › arrays.ndarray.html
The N-dimensional array (ndarray) — NumPy v2.5 Manual
That is, an ndarray can be a “view” to another ndarray, and the data it is referring to is taken care of by the “base” ndarray. ndarrays can also be views to memory owned by Python strings or objects implementing the memoryview or array interfaces. ... Try it in your browser!
🌐
Programmingforlovers
programmingforlovers.com › home › chapter 3: discovering a self-replicating automaton with top-down programming › chapter 3 python code alongs › introduction to two-dimensional arrays in python
Introduction to Two-Dimensional Arrays in Python - Programming for Lovers
June 22, 2024 - Let’s declare this array as a tuple called kernel in Python, updating main() as follows. Note that we declare the middle element as 0.0 so that Python reads it as a float instead of as an int. def main(): print("Two-dimensional arrays.") kernel = ( (0.05, 0.20, 0.05), (0.20, 0.00, 0.20), (0.05, 0.20, 0.05), ) print(kernel) if __name__ == "__main__": main()
🌐
Princeton University
introcs.cs.princeton.edu › python › 14array
Arrays in Python
Whereas the elements of a one-dimensional array are indexed by a single integer, the elements of a two-dimensional array are indexed by a pair of integers: the first specifying a row, and the second specifying a column. The simplest way to create an array in Python is to place comma-separated ...
🌐
TutorialsPoint
tutorialspoint.com › python_data_structure › python_2darray.htm
Python - 2-D Array
It is an array of arrays. In this type of array the position of an data element is referred by two indices instead of one. So it represents a table with rows an dcolumns of data. In the below example of a two dimensional array, observer that ...
Find elsewhere
🌐
CodeSignal
codesignal.com › learn › courses › multidimensional-arrays-and-their-traversal-in-python › lessons › exploring-the-dimensions-a-beginners-guide-to-multidimensional-arrays-in-python
A Beginner's Guide to Multidimensional Arrays in Python
In this example, array is a 2-dimensional array, just like a 3-storey 'apartment building,' where every floor is an inner list. All indices in Python arrays are 0-based. Let's say you want to visit an apartment on the second floor (index 1) and bring a package to the first unit (index 0) in this building.
🌐
MLJAR
mljar.com › answers › define-two-dimensional-array-python
Define two-dimensional array in Python
w = 6 # width, number of columns h = 4 # height, number of rows array = [[0 for x in range(w)] for y in range(h)]
🌐
NumPy
numpy.org › doc › 2.4 › reference › arrays.ndarray.html
The N-dimensional array (ndarray) — NumPy v2.4 Manual
That is, an ndarray can be a “view” to another ndarray, and the data it is referring to is taken care of by the “base” ndarray. ndarrays can also be views to memory owned by Python strings or objects implementing the memoryview or array interfaces. ... Try it in your browser!
🌐
Cornell Computer Science
cs.cornell.edu › courses › cs1110 › 2016sp › lectures › 05-10-16 › 27.TwoDArrays.pdf pdf
27. Two-Dimensional Arrays Topics Motivation The numpy Module Subscripting
27. Two-Dimensional Arrays · Topics · Motivation · The numpy Module · Subscripting · functions and 2d Arrays · Visualizing · A 2D array has rows and columns · This one has 3 rows and 4 columns · We say it is a “3-by-4” array (a.k.a matrix)
🌐
Processing
py.processing.org › tutorials › 2dlists
Two-Dimensional Lists \ Tutorials
Python Mode for Processing extends the Processing Development Environment with the Python programming language.
🌐
OpenGenus
iq.opengenus.org › defining-2d-array-in-python
Defining 2D array in Python
February 10, 2021 - We have explored the different ways of defining a 2D array in Python. We have explored three approaches: Creating a List of Arrays, Creating a List of Lists and creating 2D array using numpy.
🌐
Scaler
scaler.com › home › topics › matplotlib › how to visualize a 2d array?
How to Visualize a 2D Array? | Scaler Topics
June 5, 2024 - Matplotlib and Numpy provide the modules and functions to visualize a 2D array in Python. To visualize an array or list in matplotlib, we have to generate the data, which the NumPy library can do, and then plot the data using matplotlib. There are many functions by which we can add data to ...
🌐
Python Central
pythoncentral.io › how-to-initialize-a-2d-list-in-python
How to initialize a 2D List in Python? | Python Central
December 29, 2021 - The one-dimensional list of Python lists looks as follows: ... Python offers various techniques for initializing a 2D list in Python. List Comprehension is used to return a list. Python 2D list consists of nested lists as its elements. Let’s discuss each technique one by one. This technique uses List Comprehension to create Python 2D list. Here we use nested List comprehension to initialize a two-dimensional list.
🌐
Scaler
scaler.com › home › topics › 2d array in python
2D Array in Python | Python Two-Dimensional Array - Scaler Topics
May 25, 2026 - Unlike a one dimensional array, which uses a single index for individual elements, a 2D array uses two indices to locate a value. 2D arrays in python are zero-indexed, which means counting indices start from zero rather than one; thus, zero is the first index in an array in python.
🌐
OpenGenus
iq.opengenus.org › 2d-array-in-numpy
2D Arrays in NumPy (Python)
October 28, 2022 - Numpy is a library in Python adding support for large multidimensional arrays and matrices along with high level mathematical functions to operate these arrays.
🌐
Python Guides
pythonguides.com › create-a-2d-array-in-python
How to Create a 2D Array in Python
July 22, 2026 - It sorts correctly as plain text and converts reliably with Python’s datetime module, which matters for duration calculations. Once you have a nested list, read specific rows and cells using square-bracket indexing. For a 2D array, chain two indexes: row, then column.
🌐
Sololearn
sololearn.com › en › Discuss › 2304183 › can-anyone-please-explain-to-me-how-two-dimensional-arrays-run
Can anyone please explain to me how two dimensional ...
May 20, 2020 - Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.