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
🌐
Sentry
sentry.io › sentry answers › python › define a two-dimensional array in python
Define a two-dimensional array in Python | Sentry
June 15, 2023 - How can I create an empty two-dimensional array in Python, e.g. for matrix operations? The best way to create two-dimensional (2D) arrays or matrices is by using Python’s numpy module, which provides comprehensive and performant functionality for manipulating multidimensional arrays.
🌐
Reddit
reddit.com › r/learnprogramming › why are 2d arrays in python so stupid?
r/learnprogramming on Reddit: Why are 2D arrays in Python so stupid?
September 5, 2019 -

Non-shitty languages:
int[] myArray = new int[5][5]

Python:
myArray = [[0]*5]*5

Next:
myArray[1][0] = 1
print(myArray[0][0])

Non-shitty languages:
0

Python:
1

Top answer
1 of 4
5
Because they aren't arrays, and aren't designed to be pre-allocated like that. Generally, if you need matrices use Numpy.
2 of 4
4
Just because it doesn't do what you expect doesn't mean it's stupid. Stock Python doesn't really do the kind of arrays you're talking about at all, and that was a design decision. In strongly typed languages, you often have to define the size of the array before using it. You need the type so you know how much memory one element takes, then you also need to know the dimensions, so the language knows how much space to allocate. This is powerful but a bit inflexible. Python tuples act a bit like a traditional array, because they are immutable. Once you've defined them, you cannot change the size or values. You'll never make an empty tuple, because a tuple's values can't be changed. This has certain advantages, but isn't super flexible. A python list, on the other hand, is ridiculously flexible. It can contain any number of elements. Each of these elements can be any type, including another list. They don't all have to be the same type or the same length. You can change any element at any time. There's no need to predefine the size of an array, so it's not surprising that such a mechanism doesn't exist. Of course, there's plenty of ways to build an array with preset values if you really want to: HEIGHT = 3 WIDTH = 5 a = [] for i in range(HEIGHT): a.append([0]*WIDTH) There's other ways to do this that take up a lot less space, but I prefer clarity over brevity when I'm programming in Python. Note that the syntax you describe as Python's way to build a 2D array doesn't do anything in my console, and I've never seen it before. This is far more flexible and powerful than the array types of a language like Java or C++. You don't create an array of a given size in Python because you don't need to. You can always adapt a list to do whatever you want. (BTW, Java and C++ have containers that act something like Python lists, too, but they aren't usually shown to beginners.) Note that if you want to make a true 2D array, you can always use the widely available numpy module to build a matrix. You then not only have an array that acts like you're expecting, you have access to plenty of matrix operations that traditional languages don't give you. TL;DR: Python doesn't act like some language you already know. That doesn't make it bad.
Discussions

python - How to define a two-dimensional array? - Stack Overflow
Remember that python variables are untyped, but values are strongly typed. SingleNegationElimination – SingleNegationElimination · 2011-07-12 16:05:19 +00:00 Commented Jul 12, 2011 at 16:05 ... I'm confused. Coming from other languages: it IS a difference between an 1D-Array containing 1D-Arrays and a 2D-Array. And AFAIK there is no way of having a multi-dimensional-array (or list) in ... More on stackoverflow.com
🌐 stackoverflow.com
Need help with a two-dimensional array
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 ... More on discuss.python.org
🌐 discuss.python.org
0
June 3, 2022
Two dimensional array
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 ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
February 23, 2021
Is a 2d array better than two parallel arrays in python?

Your data structure is more important than performance. and parallel arrays are a terrible idea.

[a, g, t, a, g, t]
[t, c, g, a, t, c]

Consider what happens if you insert/remove an item from one array and they fall out of sync.

I'd argue the 2D array is a better data structure for what you need. I'd also argue that having each pair as it's own type is even better. Then each base pair is a single item in an array

DNA = [BasePair(a, t),  BasePair(g, c), etc]
More on reddit.com
🌐 r/learnprogramming
5
0
December 9, 2015
🌐
Guru99
guru99.com › home › python › python 2d arrays: two-dimensional list examples
Python 2D Arrays: Two-Dimensional List Examples
August 12, 2024 - In the above image, we can see that an index uniquely identifies each array element. We can create a two-dimensional array(list) with rows and columns. ... #creare 2D array with 4 rows and 5 columns array=[[23,45,43,23,45],[45,67,54,32,45],[89,90,87,65,44],[23,45,67,32,10]] #display print(array) #get the first row print(array[0]) #get the third row print(array[2]) #get the first row third element print(array[0][2]) #get the third row forth element print(array[2][3])
🌐
TutorialsPoint
tutorialspoint.com › home › python_data_structure › python 2d array
Understanding Python 2D Arrays
February 21, 2009 - Two dimensional array is an array within an 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.
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.

🌐
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).
🌐
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.
Find elsewhere
🌐
Medium
zc674.medium.com › creating-2d-arrays-in-python-207b70afe605
Creating 2D Arrays in Python. To create a 2D array in Python, I would… | by RC Chen | Medium
March 19, 2021 - Creating 2D Arrays in Python To create a 2D array in Python, I would like to discuss two ways in this blog. To create a 3*3 array in Python, one very intuitive method would be: >>> m1 = [[1] * 3] * …
🌐
AskPython
askpython.com › home › multidimensional arrays in python: a complete guide
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
🌐
NumPy
numpy.org › doc › stable › 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), ...
🌐
freeCodeCamp
freecodecamp.org › news › multi-dimensional-arrays-in-python
Multi-Dimensional Arrays in Python – Matrices Explained with Examples
December 11, 2025 - NumPy provides a powerful N-dimensional array object that you can use to create and manipulate multi-dimensional arrays efficiently. We'll now look at some examples of how to create and work with multi-dimensional arrays in Python using NumPy.
🌐
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
🌐
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))
🌐
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
🌐
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:
🌐
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
A 2D array has rows and columns. This one has 3 rows and 4 columns. ... This is row 1. ... This is column 2. ... This is the (1,2) entry. ... A list of lists. ... The numpy module makes up for this. ... A nicer notation than A[2][1]. ... Repeated append framework.
🌐
scikit-learn
scikit-learn.org › stable › modules › generated › sklearn.linear_model.LinearRegression.html
LinearRegression — scikit-learn 1.8.0 documentation
>>> import numpy as np >>> from sklearn.linear_model import LinearRegression >>> X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]]) >>> # y = 1 * x_0 + 2 * x_1 + 3 >>> y = np.dot(X, np.array([1, 2])) + 3 >>> reg = LinearRegression().fit(X, y) >>> reg.score(X, y) 1.0 >>> reg.coef_ array([1., 2.]) >>> reg.intercept_ np.float64(3.0) >>> reg.predict(np.array([[3, 5]])) array([16.])
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.html
pandas.DataFrame — pandas 3.0.1 documentation
>>> d = {"col1": [0, 1, 2, 3], "col2": pd.Series([2, 3], index=[2, 3])} >>> pd.DataFrame(data=d, index=[0, 1, 2, 3]) col1 col2 0 0 NaN 1 1 NaN 2 2 2.0 3 3 3.0 ... >>> df2 = pd.DataFrame( ... np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=["a", "b", "c"] ...
🌐
VisuAlgo
visualgo.net › en › array
Array - VisuAlgo
Note that Python list and Java ArrayList are not Linked Lists, but are actually variable-size arrays. This array visualization implements this doubling-when-full strategy. However, the classic array-based issues of space wastage and copying/shifting items overhead are still problematic. ... Counting how many values in array A is inside range [lo..hi], etc.
🌐
Matplotlib
matplotlib.org › stable › plot_types › index.html
Plot types — Matplotlib 3.10.8 documentation
Plots of the distribution of at least one variable in a dataset. Some of these methods also compute the distributions. ... Plots of arrays and images \(Z_{i, j}\) and fields \(U_{i, j}, V_{i, j}\) on regular grids and corresponding coordinate grids \(X_{i,j}, Y_{i,j}\). ... Plots of data \(Z_{x, y}\) on unstructured grids , unstructured coordinate grids \((x, y)\), and 2D functions \(f(x, y) = z\).