Demis Demis - 3 months ago 9
Python Question

How do I create dynamically, and manage, new instances of common data types in Python?

I want to make a program which will ask the user for a number (let's say 3) and create three 3x3 lists, or 3 sets of 3 members or some other complex data type (times 3) Python already knows of.

Many programs create new objects without strict programming declaration of their instances. For example in Cinema4D (3D graphics software) i can push a button and create as many cubes I want. But I don't know the programming mechanics of this automatic instance creation without a written code declaration like:

cubeobj cube_1
cube_1.name("Cube.1") ...


In C++ something like that would require the operator
new
and the function
malloc()
. Are there any equivalents for them in Python?

I've searched among many Python books and didn't find anything, what kind of Python topic would discuss something like that?

Answer

If you want a triple nested list, you can create it like this:

In [1]: num = 3

In [2]: [[[[0 for __ in range(num)] for _ in range(num)]] for ___ in range(num)]
Out[2]: 
[[[[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]]]]

Managing multidimensional arrays may be much easier with numpy though:

In [3]: import numpy as np

In [4]: np.zeros((num, num, num))
Out[4]: 
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.,  0.,  0.]]])

But the answer to your question in general is just that - you can create as many objects as you like by calling the corresponding constructor and keeping the returned instance accessible through a list, a dictionary or something else.

Using a hypothetical cube example, you can create num Cube objects and put them all in a list:

num = int(input())
cubes = [Cube(name="Cube " + str(i)) for i in range(num)]