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.

Answer from Cleb on Stack Overflow
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.

🌐
Python Guides
pythonguides.com › python-numpy-3d-array
3D Arrays In Python Using NumPy
May 16, 2025 - While Python lists and NumPy arrays are great for one and two-dimensional data, I realized that 3D arrays offer efficient capabilities for more complex data structures. In this article, I’ll share several practical ways to create and manipulate 3D arrays in Python, focusing primarily on NumPy which is the gold standard for multidimensional array operations. We’ll explore everything from ...
Discussions

python - Convert a list of 2D numpy arrays to one 3D numpy array? - Stack Overflow
I have a list of several hundred 10x10 arrays that I want to stack together into a single Nx10x10 array. At first I tried a simple newarray = np.array(mylist) But that returned with "ValueError: More on stackoverflow.com
🌐 stackoverflow.com
How to create n dimensional array in Numpy from a List?
Instead of building the array iteratively, which is relatively inefficient, you can just directly pass the list to np.array. If you need an additional size-1 dimension at the end, you can add it after: import numpy as np input="""2199943210 3987894921 9856789892 8767896789 9899965678""" input = input.split("\n") X = np.array(input)[:, np.newaxis] More on reddit.com
🌐 r/learnpython
13
2
December 9, 2021
What is 3D array in python?
1D Array: a1 = [1,2,3] 2D Array: a2 = [[1,2,3],[4,5,6],[7,8,9]] 3D Array: a3 = [ [ [1,2,3],[4,5,6],[7,8,9] ], [ [1,2,3],[4,5,6],[7,8,9] ], [ [1,2,3],[4,5,6],[7,8,9] ], ] An nD array is just a list of lists of lists n-levels down. Another way to think about is: How many indices do you need to refer to one specific element of the array? That "how many" is your n or dimensionality of the array: a1[0] # 1 index a2[0][1] # 2 indices a3[0][1][2] # 3 indices More on reddit.com
🌐 r/learnpython
10
8
February 19, 2024
Ho do do list comprehension on a numpy array?
With list comprehension: np.array([[f[i,j]/(count[i,j] or 1) for j in range(num)] for i in range(num)]) This has a corresponding performance impact because it allocates a list, then allocates an array, copies the data from the list to the new array, then deletes the original array, then deletes the list. The numpy way is this: f[count!=0] /= count[count!=0] A bit redundant still because count!=0 appears twice, but I'm not aware of a way to get rid of that. More on reddit.com
🌐 r/learnpython
2
0
September 15, 2023
🌐
Programiz
programiz.com › python-programming › numpy › ndarray-creation
NumPy N-D Array Creation (With Examples)
May 22, 2023 - We then passed the list to the np.array() function to create a 2D array. Let's say we want to create a 3-D NumPy array consisting of two "slices" where each slice has 3 rows and 4 columns. ... import numpy as np # create a 3D array with 2 "slices", each of 3 rows and 4 columns array1 = 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]]]) print(array1)
🌐
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
September 1, 2025 - 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.
🌐
GeeksforGeeks
geeksforgeeks.org › python › manipulating-multidimensional-arrays-in-python-numpy
Manipulating Multidimensional Arrays in Python NumPy - GeeksforGeeks
February 19, 2026 - 1. 2D Array from List of Lists: ... 3D Array from Nested Lists: Similarly, a 3D array can be created from a nested list structure, with each sublist representing a 2D slice of the array....
🌐
Python Like You Mean It
pythonlikeyoumeanit.com › Module3_IntroducingNumpy › FunctionsForCreatingNumpyArrays.html
Functions for Creating NumPy Arrays — Python Like You Mean It
Recall that using repeated concatenation, [0]*3 will produce [0, 0, 0]. Using this, let’s create two lists, each containing three lists, each containing four zeros; feeding this to np.array thus produces a 2x3x4 array of zeros: # A list of lists of lists of zeros creates a 3D-array >>> np.array([[[0]*4]*3]*2) 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]]])
Find elsewhere
🌐
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:
🌐
EDUCBA
educba.com › home › software development › software development tutorials › numpy tutorial › numpy 3d array
NumPy 3D array | Learn the Examples of NumPy 3D array
April 15, 2023 - In NumPy, you can create a three-dimensional array by creating an object that represents x by y by z, where x represents the outermost list, y represents the lists nested inside x, and z represents the values inside each y-nested list.
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Reddit
reddit.com › r/learnpython › how to create n dimensional array in numpy from a list?
r/learnpython on Reddit: How to create n dimensional array in Numpy from a List?
December 9, 2021 -

So this is my code:

import numpy as np

input="""2199943210
3987894921
9856789892
8767896789
9899965678"""

input = input.split("\n")

x = np.array([["2199943210"], ["3987894921"], ["9856789892"],
                ["8767896789"], ["9899965678"]])

I want to convert the input string to an ndarray like x. x i made manually by typing all that in. Can someone please tell me how to automate this? Like using a for loop & make the ndarray?

EDIT - AnSwEr FoUnD:

import numpy as np

input="""2199943210
3987894921
9856789892
8767896789
9899965678"""

input = input.split("\n")

X = np.empty(shape=[0, 1])

for i in input:
    X = np.append(X, [[i]], axis=0)

print(X)

🌐
GeeksforGeeks
geeksforgeeks.org › python-creating-3d-list
Python - Creating a 3D List - GeeksforGeeks
December 11, 2024 - The tensor() Method: To create tensors with Pytorch we can simply use the tensor() method: ... numpy.atleast_3d() function is used when we want to Convert inputs to arrays with at least three dimension.
🌐
YouTube
youtube.com › watch
How to create 3D array in NumPy Python | Module NumPy Tutorial - Part 04 - YouTube
How to create 3D (3 dimensional) array in numpy Python. In this video we will talk about how to create three dimensional arrays in module numpy Python.======...
Published: September 22, 2022
🌐
NumPy
numpy.org › doc › stable › user › basics.creation.html
Array creation — NumPy v2.5 Manual
NumPy arrays can be defined using Python sequences such as lists and tuples. Lists and tuples are defined using [...] and (...), respectively. Lists and tuples can define ndarray creation: ... further nested lists will create higher-dimensional arrays.
🌐
NumPy
numpy.org › devdocs › user › quickstart.html
NumPy quickstart — NumPy v2.6.dev0 Manual
For example, you can create an array from a regular Python list or tuple using the array function.
🌐
W3Schools
w3schools.com › python › numpy › numpy_array_reshape.asp
NumPy Array Reshaping
The outermost dimension will have 4 arrays, each with 3 elements: import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) newarr = arr.reshape(4, 3) print(newarr) Try it Yourself »
🌐
W3Schools
w3schools.com › python › numpy › numpy_creating_arrays.asp
NumPy Creating Arrays
import numpy as np arr = np.array([1, 2, 3, 4], ndmin=5) print(arr) print('number of dimensions :', arr.ndim) Try it Yourself » · In this array the innermost dimension (5th dim) has 4 elements, the 4th dim has 1 element that is the vector, the 3rd dim has 1 element that is the matrix with the vector, the 2nd dim has 1 element that is 3D array and 1st dim has 1 element that is a 4D array.
🌐
Python Like You Mean It
pythonlikeyoumeanit.com › Module3_IntroducingNumpy › AccessingDataAlongMultipleDimensions.html
Accessing Data Along Multiple Dimensions in an Array — Python Like You Mean It
Keeping track of the meaning of an array’s various dimensions can quickly become unwieldy when working with real datasets. xarray is a Python library that provides functionality comparable to NumPy, but allows users provide explicit labels for an array’s dimensions; that is, you can name each dimension. 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], ...
🌐
YouTube
youtube.com › shorts › At1dhqkVpcU
🚀 What’s a NumPy 3D Array | How to Create NumPy 3D Array #python #NumPy3D #array #coding #python - YouTube
A 3D array in NumPy is simply a list inside a list inside a list — stacked like layers 📚. Think of it as multiple 2D arrays combined into one powerful struc...
Published: February 28, 2026
🌐
NumPy
numpy.org › doc › stable › user › quickstart.html
NumPy quickstart — NumPy v2.5 Manual
For example, you can create an array from a regular Python list or tuple using the array function.