>>> a = []

>>> for i in xrange(3):
...     a.append([])
...     for j in xrange(3):
...             a[i].append(i+j)
...
>>> a
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
>>>
Answer from Perica Zivkovic 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
🌐
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.
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
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... 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
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 22, 2021
🌐
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
🌐
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
Find elsewhere
🌐
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.])
🌐
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
5 days 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.
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.

🌐
Simplilearn
simplilearn.com › home › resources › software development › data structure tutorial for beginners › 2d array: all you need to know about two-dimensional arrays
2D Array: All You Need to Know About Two-Dimensional Arrays
July 4, 2024 - An array of arrays is called a 2D array or two-dimensional array. Learn what 2D arrays are, syntax, methods, and the need for two-dimensional arrays. Read on!
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
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.