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
🌐
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
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.

Discussions

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
2D arrays in Python - Stack Overflow
In Python one would usually use lists for this purpose. Lists can be nested arbitrarily, thus allowing the creation of a 2D array. Not every sublist needs to be the same size, so that solves your other problem. More on stackoverflow.com
🌐 stackoverflow.com
Need help for Python 2D array groupby
Those aren't errors as far as I can tell. Those are just describing the objects. What is your code? More on reddit.com
🌐 r/learnpython
4
1
January 17, 2021
2D array ( list ) in Python

https://www.reddit.com/r/learnpython/wiki/faq#wiki_why_is_my_list_of_lists_behaving_strangely.3F

More on reddit.com
🌐 r/learnpython
4
1
February 27, 2018
🌐
TutorialsPoint
tutorialspoint.com › home › python_data_structure › python 2d array
Understanding Python 2D Arrays
February 21, 2009 - Explore the concept of 2D arrays in Python, including how to create and manipulate them effectively.
🌐
W3Schools
w3schools.com › python › numpy › numpy_array_shape.asp
NumPy Array Shape
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST · NumPy HOME NumPy Intro NumPy Getting Started NumPy Creating Arrays NumPy Array Indexing NumPy Array Slicing NumPy Data Types NumPy Copy vs View NumPy Array Shape NumPy Array Reshape NumPy Array Iterating NumPy Array Join NumPy Array Split NumPy Array Search NumPy Array Sort NumPy Array Filter
Find elsewhere
🌐
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.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › python tutorial › 2d arrays in python
2D Arrays In Python | Different operations in 2D arrays with Sample Code
June 29, 2023 - It can effectively perform the simplest operations like addition and subtraction to the toughest tasks like multiplication and inverse operations. Based on the requirement, they are termed two-dimensional arrays in the Python programming language in the context of data analysis.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
NumPy
numpy.org › doc › 2.2 › reference › arrays.ndarray.html
The N-dimensional array (ndarray) — NumPy v2.2 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), ...
🌐
HackerRank
hackerrank.com › domains › data-structures
Solve Programming Questions | HackerRank
Data Structures help in elegant representation of data for algorithms
🌐
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.])
🌐
MathWorks
mathworks.com › matlab › graphics › 2-d and 3-d plots › line plots
plot - 2-D line plot - MATLAB
With tall arrays, the plot function plots in iterations, progressively adding to the plot as more data is read. During the updates, a progress indicator shows the proportion of data that has been plotted. Zooming and panning is supported during the updating process, before the plot is complete.
🌐
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
In this example, array is a 2-dimensional array, just like a 3-storey 'apartment building,' where every floor is an inner list. ... All indices in Python arrays are 0-based. Let's say you want to visit an apartment on the second floor (index 1) and bring a package to the first unit (index 0) ...
🌐
Matplotlib
matplotlib.org › stable › api › _as_gen › matplotlib.pyplot.plot.html
matplotlib.pyplot.plot — Matplotlib 3.10.8 documentation
This could e.g. be a dict, a pandas.DataFrame or a structured numpy array. ... There are various ways to plot multiple sets of data. The most straight forward way is just to call plot multiple times. Example: ... If x and/or y are 2D arrays, a separate data set will be drawn for every column.
🌐
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] * …
🌐
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 (or a matrix) with three rows and three columns. Each inner list [1, 2, 3], [4, 5, 6], and [7, 8, 9] represents a row in the 2D array. When we print the array, we get the output as a nested list, which is the Pythonic way of representing a 2D array.
🌐
VisuAlgo
visualgo.net › en › array
Array - VisuAlgo
Let the compact array name be A with index [0..N-1] occupied with the items of the list.
🌐
NumPy
numpy.org › doc › stable › user › absolute_beginners.html
NumPy: the absolute basics for beginners — NumPy v2.4 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.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array
Array - JavaScript | MDN
2 weeks ago - The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name, and has members for performing common array operations.