To initialize a two-dimensional list in Python, use

t = [ [0]*3 for i in range(3)]

But don't use [[v]*n]*n, it is a trap!

>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0]=1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
Answer from Jason CHAN on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-using-2d-arrays-lists-the-right-way
Using 2D arrays/lists in Python - GeeksforGeeks
Manually initializing and populating a list without using any advanced features or constructs in Python is known as creating a 1D list using "Naive Methods". ... Explanation: [0] * N creates a list of size N. ... Explanation: range(N) controls list length. A 2D list represents data in rows and columns. Correct initialization is important to avoid unintended shared references.
Published: December 20, 2025
Discussions

Explain 2D Lists
Lists contain things. Lists are things. Therefore, lists can contain lists. That's literally all there is to it. More on reddit.com
🌐 r/learnpython
6
2
August 3, 2014
python - How to create a 2d list from a input data? - Stack Overflow
I used to do the same in C language but it works. So, how to this in Python? ... Create an empty list ar outside of loop at your declarations. More on stackoverflow.com
🌐 stackoverflow.com
python - How to define a two-dimensional array? - Stack Overflow
You can, however, create multidimensional sequences, as the answers here show. 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... More on stackoverflow.com
🌐 stackoverflow.com
2D list help in Python
Clear only clears (empties) the current instance. All your rows in your c matrix refer to the same sub_c object that you always clear. You need to create new empty sub_c lists for every single row. More on reddit.com
🌐 r/learnprogramming
6
1
January 13, 2024
🌐
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?
🌐
Du
cs.du.edu › ~intropython › intro-to-programming › 2Dlist_define.html
Defining 2D lists - Introduction to Programming
One way to create a 2D list in python is to use a 2D list literal. You've already learned how to create a 1D list literal, and the syntax here is similar.
🌐
Processing
py.processing.org › tutorials › 2dlists
Two-Dimensional Lists \ Tutorials
Python Mode for Processing extends the Processing Development Environment with the Python programming language.
🌐
Medium
medium.com › @zeebrockeraa › create-and-use-python-2d-list-169e22244ff3
Create And Use Python 2D List. In this tutorial, we’ll learn how to… | by Zeeshan Ali | Medium
July 8, 2023 - For that, we’ve to create a Python list. For demonstration, we’ll specify three lists in it. See below code: ... We now have a 2D list. Let’s now see how to fetch value of a specific item from that list.
Find elsewhere
🌐
TutorialKart
tutorialkart.com › python › how-to-create-a-2d-list-in-python
How to Create a 2D List in Python
February 14, 2025 - # Creating a 3x3 matrix filled with incremental numbers rows, cols = 3, 3 matrix = [] # Initializing matrix using nested loops for i in range(rows): row = [] for j in range(cols): row.append(i * cols + j + 1) matrix.append(row) # Printing the 2D list for row in matrix: print(row) Explanation: This code dynamically creates a 3×3 matrix where each element increases sequentially. The outer loop (for i in range(rows)) creates each row, while the inner loop (for j in range(cols)) fills each row with values. The formula i * cols + j + 1 ensures that numbers increase sequentially from 1. ... The numpy library provides an efficient way to create and manage 2D arrays.
🌐
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 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.
🌐
GeeksforGeeks
geeksforgeeks.org › python-using-2d-arrays-lists-the-right-way
Python | Using 2D arrays/lists the right way - GeeksforGeeks
The code then shows another approach using a nested list comprehension to create the 2D array arr. This method avoids aliasing by creating a new list for each row, resulting in a proper 2D array. ... # Python 3 program to demonstrate working # of method 1 and method 2.
Published: June 20, 2024
🌐
USAVPS
usavps.com › home › blog › python tutorial: how to create a 2d list in python?
Python Tutorial: How to Create a 2D List in Python? - USAVPS
March 18, 2026 - To iterate through a 2D list, you can use nested loops. The outer loop iterates through the rows, while the inner loop iterates through the columns. # Iterating through a 2D list for row in matrix: for element in row: print(element, end=' ') print() # New line after each row · Creating and manipulating 2D lists in Python is a fundamental skill that can be applied in various programming scenarios.
🌐
Guru99
guru99.com › home › python › python 2d arrays: two-dimensional list examples
Python 2D Arrays: Two-Dimensional List Examples
July 10, 2026 - Array is a data structure used to store elements. An array can only store similar types of elements. A Two Dimensional is defined as an Array inside the Array. The index of the array starts with 0 and ends with a size of array minus 1. We can create ‘n’ number of arrays in an array. 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])
Top answer
1 of 7
9

You haven't declared ar yet. In Python, you don't have to perform separate declaration and initialization; nevertheless, you can't perform operations on names willy-nilly.

Start off with something like this:

ar = [[0 for j in range(m)] for i in range(n)]
2 of 7
2

You should know that ar is not defined when you are trying to perform an assignment like ar[i][j] = int(input()), there are many ways to fix that.

In C/C++

In C/C++, I presume you would do such work like this:

#include <cstdio>

int main()
{
    int m, n;
    scanf("%d %d", &m, &n);
    int **ar = new int*[m];
    for(int i = 0; i < m; i++)
        ar[i] = new int[n];
    for(int i = 0; i < m; i++)
        for(int j = 0; j < n; j++)
            scanf("%d", &ar[i][j]);
    // Do what you want to do
    
    for(int i = 0; i < m; i++)
        delete ar[i];
    delete ar;
   
    return 0;
}

Before you get inputs by scanf in C/C++, you should allocate storage by calling new or malloc, then you can perform your scanf, or it will crash.

How to do like that in Python

It's very similar to what you had done in C/C++, according to your code, when you are trying to perform assignment to ar[i][j], Python has no idea what ar it is! So you have to let it know first.

A NOT-pythonic way

A NOT-Pythonic way is do something like you did in C/C++:

n = int(input())
m = int(input())

ar = []
for i in range(m):
    ar.append([])
    for j in range(n):
        k = int(input())
        ar[i].append(k)

for i in range(m):
    for j in range(n):
        print(ar[i][j])

You initialize the list by ar = [] like you did int **ar = new int*[m]; in C/C++. For each row in the 2-d list, initialize the row by using ar.append([]) like you did ar[i] = new int[n]; in C/C++. Then, get your data by using input and append it to ar[i].

A pythonic way

The way to perform such a job like above it's not very pythonic, instead, you can get it done by using a feature called List Comprehensions, then the code can be simplified into this:

n = int(input())
m = int(input())

ar = [[0 for j in range(n)] for i in range(m)]
for i in range(m):
    for j in range(n):
        k = int(input())
        ar[i][j] = k

for i in range(m):
    for j in range(n):
        print(ar[i][j])

Note that the core ar = [[0 for j in range(n)] for i in range(m)] is a list comprehension that it creates a list which has m lists and for each list of these m lists it has n 0s.

🌐
Dot Net Perls
dotnetperls.com › 2d-python
Python - 2D List Examples - Dot Net Perls
Detail The multiplication of the coordinates returns a single integer for a 2D point. Here We define get_element and set_element methods. We compute indexes based on an "x" and "y" coordinate pair. def get_element(elements, x, y): return elements[x + (y * 4)] def set_element(elements, x, y, value): elements[x + (y * 4)] = value # Create a list of 16 elements. elements = [] for i in range( ... Suppose it is simple to change a nested list to a flattened, 1D list.
🌐
Computer Science Newbies
csnewbs.com › python-8b-2d-lists
Python | 8b - 2D Lists | CSNewbs
Look at the table above and remember that Python starts counting at 0 so Edward is record 0, Bella 1 and Jacob 2: To print a specific data value, you need to define the record number and then the data index. ... When using 2D lists, the first value is the row, and the second value is the column. Use the table at the very top to help you visualise this: ... Use the introduction at the top to help you create a 2D list with three friends in the first column, their age in the second column and their favourite colour in the third column.
🌐
Beauty and Joy of Computing
bjc.edc.org › March2019 › bjc-r › cur › programming › old-labs › python › 2D_lists.html
2D Lists in Python
And just like in a 2D cartesian graph, retrieving an element requires two index values (essentially "the x and y position"). >>> produce = ["kale", "spinach", "sprouts"] >>> fruit = ["olives", "tomatoes", "avocado"] >>> cart = [produce, fruit] >>> cart [ ["kale", "spinach", "sprouts"], ["olives", "tomatoes", "avocado"]] The first and second list can be retrieved normally using the known notation.
🌐
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. This is a basic way to create a 2D array in Python, but there’s much more to learn about manipulating and using 2D arrays in Python.
🌐
Python Pool
pythonpool.com › home › tutorials › python 2d lists: create, index, copy, flatten, and loop
Python 2d List: From Basic to Advance
July 14, 2026 - Python lists are mutable, so updating a cell changes the structure in place. The official Python data structures tutorial explains list operations. A 2D list is not a special array type; it is a nested collection, and rows may even have different lengths unless your program enforces a rectangular shape.
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.