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 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 › 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
Discussions

How to initialize a two-dimensional array (list of lists, if not using NumPy) in Python? - Stack Overflow
When you assign to an index, it ... helped me explain with diagrams that are probably better than what I tried explaining in this comment: geeksforgeeks.org/python-using-2d-arrays-lists-the-right-way 2020-09-13T14:34:49.717Z+00:00... More on stackoverflow.com
🌐 stackoverflow.com
(Numpy) How can I generate each element of a 2d array based on a conditional statement about elements at the same coordinates in two other 2d arrays of the same dimensions?
Right of the bat you can simplify that statement. in_bounds[row, col] = (lower1 < data1[row, col] < upper1) and (lower2 < data2[row, col] < upper2) And since the matrix are only 5x5, going through nested loop is not really a problem. Unless you run that 10000 times, only then should you try to optimize it. More on reddit.com
🌐 r/learnpython
4
2
June 29, 2023
Help with matrices (without using numpy)
If A is a matrix (2D list), len(A) will be the # of rows, and len(a row) will be the # of columns. Use that to get (and compare) dimensions. AB(i,j) = (row i of A) dot (col j of B) Suppose my two matrices (A and B) are [[1,2], [[1,2,3], [3,4] and [4,5,6]] and you want the (0-based indexing) entry in row 1, col 2 that comes from [3,4] dot [3,6]. What do the indices of A look like in that row? What do the indices of B look like in that column? More on reddit.com
🌐 r/learnpython
6
8
February 19, 2021
Struggling with 2d arrays.
I was able to understand 2D arrays much better after realizing they’re basically just a grid. Imagine a 4x4 grid. That grid will range from my_array[0,0] in the top left box, all the way up to my_array[3,3] in the bottom right. In my example, my_array[0, ] are the columns and my_array[ ,0] are the rows. More on reddit.com
🌐 r/learnpython
9
1
November 25, 2024
🌐
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
🌐
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 unless we need any matrix operations.
🌐
Cf
physics-python.astro.cf.ac.uk › Week6
PX1224 -Week6: Two Dimensional Arrays
c = d2[ : :2 , : :2] print(c) Note:In the above example only the step size of 2 is specified - the start and the end rows/columns are not specified, in which case they are assumed to be the first and last column of the 2d array. A 2D array can be "sliced" to return a 1D array containing one ...
🌐
Snakify
snakify.org › two-dimensional lists (arrays)
Two-dimensional lists (arrays) - Learn Python 3 - Snakify
But the internal list can also be created using, for example, such generator: [0 for j in range(m)]. Nesting one generator into another, we obtain ... How is it related to our problem? The thing is, if the number 0 is replaced by some expression that depends on i (the line number) and j (the column number), you get the matrix filled according to some formula. For example, suppose you need to initialize the following array (for convenience, extra spaces are added between items):
🌐
AskPython
askpython.com › python › array › multidimensional-arrays
Multidimensional Arrays in Python: A Complete Guide - AskPython
February 27, 2023 - In this article, the creation and implementation of multidimensional arrays (2D, 3D as well as 4D arrays) have been covered along with examples in Python Programming language. To understand and implement multi-dimensional arrays in Python, the NumPy package is used.
Find elsewhere
🌐
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
August 28, 2026 - Python contains support for multi-dimensional arrays via immutable tuples and mutable lists; we will typically work with the latter, but will give an example of the former. In the next chapter’s homework assignment, we will work with the mysterious 3 x 3 array shown in the table below, which will help us understand how a zebra’s stripes can appear from simple patterns.
🌐
Python Guides
pythonguides.com › create-a-2d-array-in-python
2D Array in Python: Nested Lists and NumPy Examples
May 9, 2025 - Python has no built-in 2D array type, so you use either a nested list (a list of rows, like [[1, 2], [3, 4]]) or a NumPy 2D array created with np.array(), np.zeros() and similar functions.
🌐
Python Guides
pythonguides.com › initialize-a-2d-array-in-python
How to Initialize a 2D Array in Python? (2026 Guide)
September 22, 2026 - Python does not ship a dedicated 2D array type in its standard library. Lists handle the job well for most tasks. For large numeric grids, many developers reach for NumPy, a third-party library built for fast array math.
🌐
AskPython
askpython.com › python › two-dimensional-array-in-python
Two Dimensional Array in Python - AskPython
December 27, 2019 - Output-Append 2D Array · Array slicing is used to access multiple values within an array. Syntax: <slice_array> = <array>[start:stop] array1 = [[1,2,3],[4,5,6,7]] #python array slice array2 = array1[1:3] #index 1 to 2 print(array2) array2 = array1[:1] #index 0 to 1 print(array2) Output: Output-Slicing 2D Array ·
🌐
Drbeane
drbeane.github.io › python_dsci › pages › array_2d.html
2-Dimensional Arrays — Python for Data Science
Within the braces, we need to supply two numbers separated by a comma. The first number indexes a row in the array and the second number indexes a column. ... We can also use slicing with 2D arrays.
🌐
Medium
theizharahmad.medium.com › 2d-arrays-in-python-08ff7c287b2a
2D Arrays in Python. 2D arrays, also known as a matrix, are… | by Izhar Ahmad | Medium
September 7, 2024 - To represent 2D arrays in pure Python without any additional dependencies, we use the list-in-list approach.
🌐
iO Flood
ioflood.com › blog › python-2d-array
Python 2D Array with Lists | Guide (With Examples)
February 10, 2024 - In this example, we’ve created a 2D array where each element is the product of its row and column indices (starting from 1). The outer list comprehension (for i in range(1, 4)) creates the rows, and the inner list comprehension (for j in range(1, 4)) creates the elements within each row. Python’s built-in list structure is versatile and powerful, but when it comes to numerical computations and handling large 2D arrays, there’s a more efficient alternative – the numpy library.
🌐
Board Infinity
boardinfinity.com › blog › python-2d-array
Python 2D Array | Board Infinity
August 13, 2025 - ... In the code above, we multiply the array with the columns ©, now this will result in a 1D list, whose size will be equal to the number of columns. After it, we again multiply the array with the rows ®, again this will result in the ...
🌐
Scaler
scaler.com › home › topics › 2d array in python
2D Array in Python | Python Two-Dimensional Array - Scaler Topics
May 25, 2026 - We must recall that a 2D array is an array of arrays in python. Therefore we can insert a new row or element in the outer array when working with a matrix-like structure. This can be done by using the .insert() method of the array module in python; thus, we need to import the array module.
🌐
CodeSignal
codesignal.com › learn › courses › multidimensional-arrays-and-their-traversal-in-python › lessons › exploring-the-dimensions-a-beginners-guide-to-multidimensional-arrays-in-python
Exploring the Dimensions: A Beginner's Guide to Multidimensional Arrays in Python | CodeSignal Learn
To construct a multidimensional or nested array in Python, we use lists inside lists. Here's an example of a 2-dimensional array: Python · # Creating a 2D array array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(array) In this example, array is a 2-dimensional array, just like a 3-storey 'apartment ...
🌐
TutorialsPoint
tutorialspoint.com › python_data_structure › python_2darray.htm
Python - 2-D Array
We can update the entire inner array or some specific data elements of the inner array by reassigning the values using the array index.