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
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
🌐
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 › stable › reference › arrays.ndarray.html
The N-dimensional array (ndarray) — NumPy v2.5 Manual
The type of items in the array is specified by a separate data-type object (dtype), one of which is associated with each ndarray. As with other container objects in Python, the contents of an ndarray can be accessed and modified by indexing or slicing the array (using, for example, N integers), ...
🌐
YouTube
youtube.com › watch
Python 2D collections are easy! ⬜ - YouTube
#python #tutorial #course 00:00:00 intro00:06:11 exerciseHere are a few different 2d collection combinations:# 2D list of listsnum_pad = [[1, 2, 3],
Published: November 8, 2022
🌐
TutorialsPoint
tutorialspoint.com › python_data_structure › python_2darray.htm
Python - 2-D Array
Python TechnologiesDatabasesComputer ... QualityManagement Tutorials View All Categories ... Two dimensional array is an array within an array....
🌐
YouTube
youtube.com › reallifeed
Python 2D arrays and lists - YouTube
How to use 2D Arrays and Lists. Python Programming Beginners series.In this video:- 2D Arrays- 2D ListsTools:The Python Standard Library - https://docs.pyth...
Published: October 24, 2022
Find elsewhere
🌐
W3Schools
w3schools.com › python › numpy › numpy_creating_arrays.asp
NumPy Creating Arrays
NumPy is used to work with arrays. The array object in NumPy is called ndarray.
🌐
Google
sites.google.com › rgc.aberdeen.sch.uk › rgcahcomputingrevision › software-design › data-types-and-structures › 2d-arrays
Advanced Higher Computing Revision - 2D Arrays
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.
🌐
Sentry
sentry.io › sentry answers › python › define a two-dimensional array in python
Define a two-dimensional array in Python | Sentry
June 15, 2023 - import numpy matrix = ... this operation. To create a 2D array without using numpy, we can initialize a list of lists using a list comprehension....
🌐
NumPy
numpy.org › devdocs › user › absolute_beginners.html
NumPy: the absolute basics for beginners — NumPy v2.6.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.
🌐
Snakify
snakify.org › two-dimensional lists (arrays)
Two-dimensional lists (arrays) - Learn Python 3 - Snakify
In real-world Often tasks have to store rectangular data table. [say more on this!] Such tables are called matrices or two-dimensional arrays. In Python any table can be represented as a list of lists (a list, where each element is in turn a list).
🌐
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
To construct a multidimensional or nested array in Python, we use lists inside lists. Here's an example of a 2-dimensional array: # 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 building,' ...
🌐
W3Schools
w3schools.com › python › python_arrays.asp
Python Arrays
Arrays are used to store multiple values in one single variable.
🌐
DataCamp
campus.datacamp.com › courses › introduction-to-python-for-finance › arrays-in-python
2D arrays and functions | Python
But instead of providing a single list as the input, you pass in a list of two lists as the input as shown here. In this case, we've passed two lists, months and prices, to create a 2D array.
🌐
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:
🌐
Cf
physics-python.astro.cf.ac.uk › Week6
PX1224 -Week6: Two Dimensional Arrays
2-d Arrays can be multiplied just as 1-d arrays can be; all mathematical operations that work with single variables (i.e. single numbers) (addition, subtraction, division, raising to a power, sin etc.) work with 2D arrays element-by-element. It is possible to find the maximum entry in a 2-d array, however, if you try using python's max() function, you will get an error
🌐
NumPy
numpy.org › doc › 2.4 › reference › arrays.ndarray.html
The N-dimensional array (ndarray) — NumPy v2.4 Manual
The type of items in the array is specified by a separate data-type object (dtype), one of which is associated with each ndarray. As with other container objects in Python, the contents of an ndarray can be accessed and modified by indexing or slicing the array (using, for example, N integers), ...
🌐
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
2d Arrays in Python · A = [[12,17,49,61],[38,18,82,77],[83,53,12,10]] A list of lists. 12 17 49 61 · 38 18 82 77 · 83 53 12 10 · Accessing Entries · A = [[12,17,49,61],[38,18,82,77],[83,53,12,10]] A[1][2] 12 17 49 61 · 38 18 82 77 · 83 53 12 10 · Accessing Entries ·