You should use a list comprehension:

>>> import pprint
>>> n = 3
>>> distance = [[[0 for k in xrange(n)] for j in xrange(n)] for i in xrange(n)]
>>> pprint.pprint(distance)
[[[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, 0, 0]]]
>>> distance[0][1]
[0, 0, 0]
>>> distance[0][1][2]
0

You could have produced a data structure with a statement that looked like the one you tried, but it would have had side effects since the inner lists are copy-by-reference:

>>> distance=[[[0]*n]*n]*n
>>> pprint.pprint(distance)
[[[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, 0, 0]]]
>>> distance[0][0][0] = 1
>>> pprint.pprint(distance)
[[[1, 0, 0], [1, 0, 0], [1, 0, 0]],
 [[1, 0, 0], [1, 0, 0], [1, 0, 0]],
 [[1, 0, 0], [1, 0, 0], [1, 0, 0]]]
Answer from robert on Stack Overflow
🌐
w3resource
w3resource.com › python-exercises › list › python-data-type-list-exercise-13.php
Python: Generate a 3D array - w3resource
The ' * ' character is assigned to every element of the innermost list using the list comprehension. So, the resulting array is a 3D array of size 3x4x6, with every element initialized to the character '*'. Finally print() function prints the said array. ... Write a Python program to generate a 3D array where each element is its coordinate sum.
🌐
w3resource
w3resource.com › python-exercises › numpy › convert-a-list-of-lists-of-lists-to-a-3d-numpy-array-and-print.php
Convert a list of lists of lists to a 3D NumPy array and print
Define Nested List: Create a nested list of lists of lists with some example data. Convert to 3D NumPy Array: Use the np.array() function to convert the nested list into a 3D NumPy array.
🌐
Python Guides
pythonguides.com › python-numpy-3d-array
3D Arrays In Python Using NumPy
May 16, 2025 - import numpy as np # Create a 3D array with zeros - great for initializing zeros_array = np.zeros((2, 3, 4)) # 2 matrices, 3 rows, 4 columns # Create a 3D array with ones ones_array = np.ones((2, 3, 4)) # Create a 3D array with random values random_array = np.random.rand(2, 3, 4) # Create from nested lists list_array = np.array([ [[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]] ]) print(f"Shape of array: {list_array.shape}") ... I expected the above example code and added the screenshot below. Using NumPy to work with 3D arrays ensures better performance and easier manipulation compared to plain Python lists
🌐
GeeksforGeeks
geeksforgeeks.org › python-creating-3d-list
Python - Creating a 3D List - GeeksforGeeks
December 11, 2024 - Scalar, 1 and 2 dimensional inputs are converted to 3-dimensional arrays, whilst higher-dimensional inputs are preserved. Input includes scalar, lists, lists of tuples, tuples, tuples of tuple ... Heatmaps are a great way to visualize a dataset, methods for visualizing the data are getting explored constantly and 3D heatmap is one of the ways to plot data. Let's learn how we can plot 3D data in python.
Top answer
1 of 5
4

The answers by @SonderingNarcissit and @MadPhysicist are already quite nice.

Here is a quick way of adding a number to each element in your list and keeping the structure. You can replace the function return_number by anything you like, if you want to not only add a number but do something else with it:

def return_number(my_number):
    return my_number + 4    

def add_number(my_list):

    if isinstance(my_list, (int, float)):
        return return_number(my_list)
    else:
        return [add_number(xi) for xi in my_list]

A = [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0], [0], [0]]]

Then

print(add_number(A))

gives you the desired output:

[[[4, 4, 4], [4, 4, 4], [4, 4, 4]], [[4], [4], [4]]]

So what it does is that it look recursively through your list of lists and everytime it finds a number it adds the value 4; this should work for arbitrarily deep nested lists. That currently only works for numbers and lists; if you also have e.g. also dictionaries in your lists then you would have to add another if-clause.

2 of 5
2

Since numpy can only work with regular-shaped arrays, it checks that all the elements of a nested iterable are the same length for a given dimension. If they are not, it still creates an array, but of type np.object instead of np.int as you would expect:

>>> B = np.array(A)
>>> B
array([[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
       [[0], [0], [0]]], dtype=object)

In this case, the "objects" are lists. Addition is defined for lists, but only in terms of other lists that extend the original, hence your error. [0, 0] + 4 is an error, while [0, 0] + [4] is [0, 0, 4]. Neither is what you want.

It may be interesting that numpy will make the object portion of your array nest as low as possible. Array you created is actually a 2D numpy array containing lists, not a 1D array containing nested lists:

>>> B[0, 0]
[0, 0, 0]
>>> B[0, 0, 0]
Traceback (most recent call last):

  File "<ipython-input-438-464a9bfa40bf>", line 1, in <module>
    B[0, 0, 0]

IndexError: too many indices for array

As you pointed out, you have two options when it comes to ragged arrays. The first is to pad the array so it is non-ragged, convert it to numpy, and only use the elements you care about. This does not seem very convenient in your case.

The other method is to apply functions to your nested array directly. Luckily for you, I wrote a snippet/recipe in response to this question, which does exactly what you need, down to being able to support arbitrary levels of nesting and your choice of operators. I have upgraded it here to accept non-iterable nested elements anywhere along the list, including the original input and do a primitive form of broadcasting:

from itertools import repeat

def elementwiseApply(op, *iters):
    def isIterable(x):
        """
        This function is also defined in numpy as `numpy.iterable`.
        """
        try:
            iter(x)
        except TypeError:
            return False
        return True

    def apply(op, *items):
        """
        Applies the operator to the given arguments. If any of the
        arguments are iterable, the non-iterables are broadcast by
        `itertools.repeat` and the function is applied recursively
        on each element of the zipped result.
        """
        elements = []
        count = 0
        for iter in items:
            if isIterable(iter):
                elements.append(iter)
                count += 1
            else:
                elements.append(itertools.repeat(iter))
        if count == 0:
            return op(*items)
        return [apply(op, *items) for items in zip(*elements)]

    return apply(op, *iters)

This is a pretty general solution that will work with just about any kind of input. Here are a couple of sample runs showing how it is relevant to your question:

>>> from operator import add
>>> elementwiseApply(add, 4, 4)
8
>>> elementwiseApply(add, [4, 0], 4)
[8, 4]
>>> elementwiseApply(add, [(4,), [0, (1, 3, [1, 1, 1])]], 4)
[[8], [4, [5, 7, [5, 5, 5]]]]
>>> elementwiseApply(add, [[0, 0, 0], [0, 0], 0], [[4, 4, 4], [4, 4], 4])
[[4, 4, 4], [4, 4], 4]
>>> elementwiseApply(add, [(4,), [0, (1, 3, [1, 1, 1])]], [1, 1, 1])
[[5], [1, [2, 4, [2, 2, 2]]]]

The result is always a new list or scalar, depending on the types of the inputs. The number of inputs must be the number accepted by the operator. operator.add always takes two inputs, for example.

🌐
EDUCBA
educba.com › home › software development › software development tutorials › python tutorial › 3d arrays in python
3d Arrays in Python | How to Create,Insert And Remove 3D Array In Python
April 23, 2024 - And the answer is we can go with the simple implementation of 3d arrays with the list. But for some complex structures, we have an easy way of doing it by including Numpy. It is not recommended which way to use it. It depends on the project and requirement of how you want to implement a particular functionality. Python has a set of libraries defines to ease the task.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
Find elsewhere
🌐
Python Examples
pythonexamples.org › python-numpy-create-3d-array
Create 3D Array in NumPy
To create a 3D (3 dimensional) array in Python using NumPy library, we can use any of the following methods. ... Pass a nested list (list of lists of lists) to numpy.array() function.
🌐
Delft Stack
delftstack.com › home › howto › python › declare 3d array in python
How to Declare 3D Array in Python | Delft Stack
February 2, 2024 - The following code example shows us how we can use the list comprehensions to declare a 3D array in Python.
🌐
TutorialsPoint
tutorialspoint.com › python-program-to-create-3d-list
Python program to create 3D list.
In the following example, we are going to create a 3D list with the sequential numbers starting from 1. a, b, c = 2, 2, 3 x = 1 y = [] for i in range(a): z = [] for j in range(b): row = [] for k in range(c): row.append(x) x += 1 z.append(row) y.append(z) print("Result :") print(y) ... The Python ...
🌐
Python Like You Mean It
pythonlikeyoumeanit.com › Module3_IntroducingNumpy › AccessingDataAlongMultipleDimensions.html
Accessing Data Along Multiple Dimensions in an Array — Python Like You Mean It
Using an xarray to select Brad’s scores could look like grades.sel(student='Brad'), for instance. This is a valuable library to look into at your leisure. Let’s build up some intuition for arrays with a dimensionality higher than 2. The following code creates a 3-dimensional array: # a 3D array, shape-(2, 2, 2) >>> d3_array = np.array([[[0, 1], ...
🌐
Quora
quora.com › How-can-you-create-an-array-3D-in-Python
How to create an array 3D in Python - Quora
Answer: In Python, you can create a 3D array using lists or, preferably, NumPy arrays. NumPy is a powerful library for numerical operations, and it provides convenient functions for working with multi-dimensional arrays. Here's how you can create a 3D array using NumPy:
🌐
Reddit
reddit.com › r/learnpython › declaring a 3d array (list?) in python
r/learnpython on Reddit: Declaring a 3D array (list?) in Python
November 8, 2013 -

Hello friends. I am trying to start to learn Python, but I am having some trouble getting past the early steps. I have a working knowledge of C and have figured out how to transfer most things over to the new syntax, but this one eludes me. I would like to declare a three dimensional array, which I believe may be called a list in Python, similar to this example in C:

int map[2][3][5] = {{
{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},
{0,0,0,0,0}}}

Please note I may have gotten my bracketing slightly wrong here. I always get confused without a compiler to correct me, but you know what I'm going for - an expandable set of 2D arrays I can define when they are initialized.

My issue is finding documentation that allows me to declare and reference a variable in this way. I need the program to be able to hit specific tiles, such as map[1][2][0] vs. map[1][2][1], and all the information I've found regarding declarations for Python seem to lean towards not defining these borders and having these vaguely long lists that I'm not sure how to manage properly. I thought I might be missing something, possibly searching for the wrong words (Is it called a 3D list? Who knows!) or looking in the wrong areas. If this is an easy thing to look up, I'm sorry, I've tried over and over before posting and I just can't get it to come up with what I need. Any help would be greatly appreciated!

As a final note, this is one of the first things I need to figure out to teach myself Python, so it would be best to assume I have little knowledge of the terminology and syntax. All my programming before this was straight C, not even C++ really, so it is very foreign looking to me.

Top answer
1 of 5
5
First of all, you wouldn't get confused with your bracketing if you wrote it a little differently: int map[2][3][5] = { { {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}, {0,0,0,0,0} } } Anyway, you basically have two options: Option 1: list of lists of lists x, y, z = 2, 3, 5 map = [] for _ in range(x): sublist = [] for _ in range(y): subsublist = [0] * z sublist.append(subsublist) map.append(sublist) This can be written more compactly using nested list comprehensions: x, y, z = 2, 3, 5 map = [[[0 for c in range(z)] for b in range(y)] for a in range(x)] Doing it this way, your dimensions are fixed size (you'll get IndexError if you try to access invalid indices), but it is non-ideal because it is really a list of lists of lists. You'll have to be careful not to accidentally make multiple references to the same sublists, because that would probably lead to confusing unexpected results. Option 2: dictionary with (x, y, z) tuples as the keys x, y, z = 2, 3, 5 map = {(a, b, c): 0 for a in range(x) for b in range(y) for c in range(z)} # Now access items like map[(2, 3, 5)] # or even map[2, 3, 5] This is nice because the set-up is simpler. The downside is that there's no safeguard against adding new items with out-of-bounds indices. EDIT: Probably a good idea to call this something other than map, because map() is a built-in function that you may find yourself needing to use.
2 of 5
4
n-dimensional arrays in python can be represented as just lists of lists. Are you familiar with how to make a single list?
🌐
Medium
medium.com › @bouimouass.o › what-3d-arrays-look-like-some-ways-to-construct-them-and-their-applications-5f054ce9adb8
What 3D arrays look like, some ways to construct them and their applications? | by Omar | Medium
July 23, 2023 - There are three ways to construct 3D arrays in Python: ... # Using the array() function array = np.array([[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], [[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]]) # Using the reshape() function ...
🌐
EyeHunts
tutorial.eyehunts.com › home › 3d array python
3D array Python
July 3, 2023 - Here’s an example of a simple ... 19, 20], [21, 22, 23, 24] ] ] In Python, you can create a 3D array using nested lists or by using libraries like NumPy....