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
1261

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
486

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
🌐
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):
🌐
TutorialsPoint
tutorialspoint.com › home › python_data_structure › python 2d array
Python 2D Array
February 21, 2009 - Explore the concept of 2D arrays in Python, including how to create and manipulate them effectively.
🌐
Drbeane
drbeane.github.io › python_dsci › pages › array_2d.html
2-Dimensional Arrays — Python for Data Science
Before we demonstrate this, we will first explore the default behavior of the np.sum() function on 2D arrays. In the cell below, we create an array with shape (2,4).
🌐
DataCamp
campus.datacamp.com › courses › intro-to-python-for-data-science › chapter-4-numpy
2D NumPy Arrays | Python
The arrays np_height and np_weight are one-dimensional arrays, but it's perfectly possible to create 2 dimensional, three dimensional, heck even seven dimensional arrays! Let's stick to 2 in this video though. You can create a 2D numpy array from a regular Python list of lists.
🌐
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)] ... REMEMBER Be careful with idexing, you can't go out of range! ... This way is much easier. You can use zeros function from numpy to create 2D array with all values set to zero:
Find elsewhere
🌐
W3docs
w3docs.com › python
How to initialize a two-dimensional array in Python?
Here is an example of how to create a 2D array with 3 rows and 4 columns, filled with zeroes: # create a 2D array with 3 rows and 4 columns, filled with zeroes rows = 3 cols = 4 arr = [[0 for j in range(cols)] for i in range(rows)] print(arr)
🌐
Google
sites.google.com › rgc.aberdeen.sch.uk › rgcahcomputingrevision › software-design › data-types-and-structures › 2d-arrays
Advanced Higher Computing Revision - 2D Arrays
When declaring a 2 dimensional (2D) array we specify the rows and columns · Python treats this as a list within a list. You will notice that we have initialised each element in the array with a value of 0. This would create a 2D array called my2dArray with 3 rows and 8 columns.
🌐
NumPy
numpy.org › devdocs › user › absolute_beginners.html
NumPy: the absolute basics for beginners — NumPy v2.5.dev0 Manual
Using np.newaxis will increase the dimensions of your array by one dimension when used once. This means that a 1D array will become a 2D array, a 2D array will become a 3D array, and so on.
🌐
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
🌐
freeCodeCamp
forum.freecodecamp.org › python
Two dimensional array - Python - The freeCodeCamp Forum
February 23, 2021 - Write a Python program which takes two digits as input and generates a two dimentional array. row = int(input('Enter the number of row :')) col = int(input('Enter the number of columns : ')) multi_list = [[0 for col in range(col)], [0 for row in range(row)]] for i in range(row): for j in range(col): multi_list[row][col] = row * col print(multi_list) #Error message : Syntax Error: invalid syntax (for i in range(row))
🌐
Python.org
discuss.python.org › python help
Need help with a two-dimensional array - Python Help - Discussions on Python.org
June 2, 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.
🌐
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
Our goal today is to strengthen your foundational knowledge of these 'apartment buildings' and how to handle them effectively in Python. ... To construct a multidimensional or nested array in Python, we use lists inside lists.
🌐
Python Guides
pythonguides.com › python-numpy-2d-array
Create A 2D NumPy Array In Python (5 Simple Methods)
May 16, 2025 - The most common way to create a 2D NumPy array is by using the numpy.array() function. This method converts nested Python lists into a multidimensional array.
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › 2d array in python
Comprehensive Guide to 2D Arrays in Python: Creation, Access, and Use
September 12, 2024 - When accessing elements in a 2D array, be cautious about boundary conditions to avoid Python 2d list indexing errors. Ensure that your code accounts for edge cases, such as the first and last rows and columns. ... # Check if a specific element is within bounds if 0 <= row < num_rows and 0 <= col < num_cols: value = array[row][col] else: print("Element is out of bounds.") ... 2d list Python comprehension is a concise and readable way to create and modify 2D arrays.
🌐
Scaler
scaler.com › home › topics › 2d array in python
2D Array in Python | Python Two-Dimensional Array - Scaler Topics
October 10, 2025 - There is another syntax for creating a 2D array where initialization (creation of array and addition of elements) is done with a single line of code. This syntax is as follows: Where array_name is the array's name, r1c1, r1c1 etc., are elements of the array. Here r1c1 means that it is the element of the first column of the first row. A 2D array is an array of arrays. We can directly access values or elements of a 2D array in Python.
🌐
Edureka
edureka.co › blog › 2d-arrays-in-python
2D Arrays In Python | Implementing Arrays In Python | Edureka
November 27, 2024 - So we all know arrays are not present as a separate object in python but we can use list object to define and use it as an array. For example, consider an array of ten numbers: A = {1,2,3,4,5} Syntax used to declare an array: ... Moving with this article on 2D arrays in Python.