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
🌐
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.
🌐
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.
🌐
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
🌐
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):
🌐
Cf
physics-python.astro.cf.ac.uk › Week6
PX1224 -Week6: Two Dimensional Arrays
Full colour images actually store 3 values, "redness", "blueness" and "greeness" for each value, so can be thought of as three 2D arrays. Alternatively, a 3D array, eg 1200 elements by 800 elements (ie a screen resolution of 1200x800) by 3 elements can represent a full colour image on the screen. To generate an image like this, we first want to create x and y arrays using mgrid(), then calculate a "height" value, z, at each point in x and y. Finally, we plot a contour plot using the values of z to give the colours. The code to do this is given below · Python can show such images.
Find elsewhere
🌐
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
🌐
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: 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 ...
🌐
NumPy
numpy.org › doc › stable › user › basics.creation.html
Array creation — NumPy v2.5 Manual
NumPy arrays can be defined using Python sequences such as lists and tuples. Lists and tuples are defined using [...] and (...), respectively. Lists and tuples can define ndarray creation: a list of numbers will create a 1D array, a list of lists will create a 2D array, further nested lists will create higher-dimensional arrays.
🌐
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.
🌐
Wikipedia
en.wikipedia.org › wiki › Array_(data_structure)
Array (data structure) - Wikipedia
September 21, 2026 - Often the coefficients are chosen so that the elements occupy a contiguous area of memory. However, that is not necessary. Even if arrays are always created with contiguous elements, some array slicing operations may create non-contiguous sub-arrays from them.
🌐
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 - 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.
🌐
LabEx
labex.io › tutorials › python-how-to-create-2d-arrays-efficiently-420183
How to create 2D arrays efficiently | LabEx
By mastering various array creation methods and practical operations, programmers can optimize their data manipulation strategies and improve computational performance. A 2D array is a structured collection of elements arranged in rows and columns, essentially a matrix or table-like data structure in Python.
🌐
Blender
blender.org
Blender - The Free and Open Source 3D Creation Software — blender.org
It opens unsurpassed workflow freedom for story-boarders and 2D artists. ... Blender has a flexible Python controlled interface. Layout, colors, size and even fonts can be adjusted. Use hundreds of add-ons by the community or create your own using Blender’s accessible Python API.
🌐
Python.org
discuss.python.org › python help › need help with a two-dimensional array
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.
🌐
Scribd
scribd.com › document › 346185163 › pythonlist-1
Declaring 2D Arrays in Python | PDF | Array Data Type | Software Engineering
The document discusses ways to declare and initialize two-dimensional arrays or lists in Python. It notes that Python does not have true multidimensional arrays, but instead uses lists of lists. Several methods are provided to dynamically initialize lists of lists, including using list comprehensions and appending empty lists.
🌐
Guru99
guru99.com › home › python › python 2d arrays: two-dimensional list examples
Python 2D Arrays: Two-Dimensional List Examples
October 7, 2026 - Python 2D Array is an array placed inside another array, forming rows and columns like a table. The examples below show how to create, access, insert, update, delete, and size 2D arrays.
🌐
Python Tutor
pythontutor.com › visualize.html
Python Tutor - Visualize Code Execution
(1) Go to pythontutor.com and select a language. Here the user chose Java and wrote code to recursively create a LinkedList.
🌐
OpenGenus
iq.opengenus.org › 2d-array-in-numpy
2D Arrays in NumPy (Python)
October 28, 2022 - Random Array random.rand(r,c) - this function will generate an array with all random elements.