Nest lists in lists you don't need to predefine the length of a list to use it and you can append on to it. Want another dimension simply append another list to the inner most list.

[[[a1, a2, a3]  , [b1, b2, b3] , [c1, c2, c3]],
[[d1, d2, d3]  , [e1, e2, e3] , [f1, f2, f3]]]

and to use them easily just look at Nested List Comprehensions

Answer from VoronoiPotato on Stack Overflow
Discussions

How to define a dynamic two-dimensional array in python? - Stack Overflow
I want to define a dynamic two-dimensional array in python. I don't know how many rows my two-dimensional array will have at the start of my program. I would like to define new rows in this 2D arr... More on stackoverflow.com
๐ŸŒ stackoverflow.com
July 13, 2011
python - Create a dynamic 2D numpy array on the fly - Stack Overflow
Depending on what create_row() ... the Python loop altogether. ... Sign up to request clarification or add additional context in comments. ... Just pass the list of lists to numpy.array, keep in mind that numpy arrays are ndarrays, so the concept to a list of lists doesn't translate to arrays of arrays it translates to a 2d ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Two Dimensional List - dynamically creating it does not work, while manually works fine.
As you can see, multiplying just gives you several references to the same sublist. Instead you should loop, eg with a list comprehension: self.grid = [[0] * self.sizeY for _ in range(self.sizeX)] More on reddit.com
๐ŸŒ r/learnpython
4
2
January 8, 2024
Creating a dynamic array in python - Stack Overflow
I have a dynamic array in which I would like to update the userstring, e.g., for a 25 character single string like 'mannysattynastysillyfully'. there would be a 5x5 array . m a n n y s a t t y n a... More on stackoverflow.com
๐ŸŒ stackoverflow.com
March 21, 2017
๐ŸŒ
YouTube
youtube.com โ€บ watch
Python declaring dynamic arrays and multi-dimensional arrays - YouTube
How to declare dynamic arrays?How to declare multi-dimensional arrays?List is a dynamic arrays in pythonyou can append or fill values2 or more dimensional li...
Published: August 14, 2019
๐ŸŒ
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
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-using-2d-arrays-lists-the-right-way
Python | Using 2D arrays/lists the right way - GeeksforGeeks
A 2D array is essentially a list of lists, which represents a table-like structure with rows and columns. In Python, Initializing a collection of elements in a linear sequence requires creating a 1D array, which is a fundamental process.
Published: June 20, 2024
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ two dimensional list - dynamically creating it does not work, while manually works fine.
r/learnpython on Reddit: Two Dimensional List - dynamically creating it does not work, while manually works fine.
January 8, 2024 -

I have a class where it should create a 2D list depending on the given size x and y. However, noticed that the following does not work.

self.grid = [[0] * self.sizeY] * self.sizeX
self.grid[1][0] = "TEST"

The output:

[['TEST', 0, 0, 0, 0], ['TEST', 0, 0, 0, 0], ['TEST', 0, 0, 0, 0], ['TEST', 0, 0, 0, 0], ['TEST', 0, 0, 0, 0]]

While the following works fine as expected:

self.grid = [[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]]
self.grid[1][0] = "TEST"

The output:

[[0, 0, 0, 0, 0], ['TEST', 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

As you can see in the first example when the result is not what is expected, location [1][0] is being stored 5 times as if all 'rows' are the same.

Any ideas on how to create the 2D list dynamically?

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ implementation-of-dynamic-array-in-python
Implementation of Dynamic Array in Python - GeeksforGeeks
May 12, 2023 - import ctypes class DynamicArray(object): ''' DYNAMIC ARRAY CLASS (Similar to Python List) ''' def __init__(self): self.n = 0 # Count actual elements (Default is 0) self.capacity = 1 # Default Capacity self.A = self.make_array(self.capacity) def __len__(self): """ Return number of elements stored in array """ return self.n def __getitem__(self, k): """ Return element at index k """ if not 0 <= k < self.n: # Check it k index is in bounds of array return IndexError('K is out of bounds !') return self.A[k] # Retrieve from the array at index k def append(self, ele): """ Add element to end of the array """ if self.n == self.capacity: # Double capacity if not enough room self._resize(2 * self.capacity) self.A[self.n] = ele # Set self.n index to element self.n += 1 def insertAt(self, item, index): """ This function inserts the item at any specified index.
๐ŸŒ
YouTube
youtube.com โ€บ blogize
Creating and Appending to 2D Arrays in Python for Dynamic Data Storage - YouTube
Summary: Learn how to create and dynamically append to 2D arrays in Python. Discover the flexibility of using lists, tuples, and multidimensional arrays for ...
Published: October 29, 2024
Views: 8
๐ŸŒ
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
To process 2-dimensional array, you typically use nested loops. The first loop iterates through the row number, the second loop runs through the elements inside of a row.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python_data_structure โ€บ python_2darray.htm
Python - 2-D Array
We can update the entire inner array or some specific data elements of the inner array by reassigning the values using the array index.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ 2d array in python
2D Array in Python | Python Two-Dimensional Array - Scaler Topics
May 25, 2026 - Unlike a one dimensional array, which uses a single index for individual elements, a 2D array uses two indices to locate a value. 2D arrays in python are zero-indexed, which means counting indices start from zero rather than one; thus, zero is the first index in an array in python.
Top answer
1 of 1
2

I think this may do what you are after:

>>> def two_dim(inval, width=5):
...     out = []
...     for i in range(0, len(inval) - 1, width):
...         out.append(list(inval[i:i + width]))
...     return out
...
>>> print(two_dim('mannysattynastysillyfully'))
[['m', 'a', 'n', 'n', 'y'], ['s', 'a', 't', 't', 'y'], ['n', 'a', 's', 't', 'y'], ['s', 'i', 'l', 'l', 'y'], ['f', 'u', 'l', 'l', 'y']]

And to print it like you have in the question:

>>> c = two_dim('mannysattynastysillyfully')
>>> for sub in c:
...     print " ".join(sub)
...
m a n n y
s a t t y
n a s t y
s i l l y
f u l l y

NOTE This will only create complete rows, so using a width that is not a factor of the length of the input string will result in lost data. This is easy to change if desired, but I will leave that as an exercise to the reader.

If you are looking to always create a square 2x2, then you could do something like

def is_square(l):
    return math.floor(math.sqrt(l))**2 == l

def two_dim_square(inval):
    if not is_square(len(inval)):
        raise Exception("string length is not a perfect square")
    width = math.sqrt(len(inval))
    # proceed like before with a derived width

EDIT 2

def two_dim(inval, width=5):
    out = []
    for i in range(0, len(inval) - 1, width):
        out.append(list(inval[i:i + width]))
    return out

def print_array(label, inval, joiner=' '):
    print label
    for sub in inval:
        print joiner.join(sub)
    print

print_array("3 by X", two_dim('mannysattynastysillyfully', 3))
print_array("4 by X", two_dim('mannysattynastysillyfully', 4))
print_array("5 by X", two_dim('mannysattynastysillyfully', 5))
print_array("6 by X", two_dim('mannysattynastysillyfully', 6))

Gives the output

3 by X
m a n
n y s
a t t
y n a
s t y
s i l
l y f
u l l

4 by X
m a n n
y s a t
t y n a
s t y s
i l l y
f u l l

5 by X
m a n n y
s a t t y
n a s t y
s i l l y
f u l l y

6 by X
m a n n y s
a t t y n a
s t y s i l
l y f u l l

EDIT 3
If you want all data to always be present, and use a default value for empty cells, then that would look like

def two_dim(inval, width=5, fill=' '):
    out = []
    # This just right-pads the input string with the correct number of fill values so the N*M is complete.
    inval = inval + (fill * (width - (len(inval) % width)))
    for i in range(0, len(inval) - 1, width):
        out.append(list(inval[i:i + width]))
    return out

Called with

print_array("3 by X", two_dim('mannysattynastysillyfully', 3, '*'))

OUTPUT

3 by X
m a n
n y s
a t t
y n a
s t y
s i l
l y f
u l l
y * *
๐ŸŒ
AskPython
askpython.com โ€บ python โ€บ two-dimensional-array-in-python
Two Dimensional Array in Python - AskPython
December 27, 2019 - Output-Append 2D Array ยท Array slicing is used to access multiple values within an array. Syntax: <slice_array> = <array>[start:stop] array1 = [[1,2,3],[4,5,6,7]] #python array slice array2 = array1[1:3] #index 1 to 2 print(array2) array2 = array1[:1] #index 0 to 1 print(array2) Output: Output-Slicing 2D Array ยท
๐ŸŒ
YouTube
youtube.com โ€บ watch
Create Two Dimensional Array using Numpy in Python | Jupyter Notebood | Python for beginners - 106 - YouTube
Create Two Dimensional Array using Numpy in Python | Jupyter Notebood | Python for beginners - 106Your learn in this video how to create two dimensional arra...
Published: December 19, 2023
๐ŸŒ
DaniWeb
daniweb.com โ€บ programming โ€บ software-development โ€บ threads โ€บ 160559 โ€บ empty-2d-array
python - Empty 2D Array [SOLVED] | DaniWeb
December 3, 2008 - For heavy numeric work, prefer NumPy arrays for performance and vectorization; initialize once you know dimensions: arr = numpy.zeros((rows, cols)) (NumPy zeros). More on the aliasing gotcha: Python FAQ: multidimensional lists. defaultdict docs: collections.defaultdict. hoe to write a generic code for creating a empty 2D array and dynamically insert values in it.
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.