Skip to content Skip to sidebar Skip to footer

Creating A Nested List In Python

I'm trying to make a nested list in Python to contain information about points in a video, and I'm having a lot of trouble creating an array for the results to be saved in to. The

Solution 1:

This illustrates what is going on:

In [1334]:step=[[0]*3forxinrange(3)]In [1335]:stepOut[1335]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
In [1336]:stack=[step]*4In [1337]:stackOut[1337]: 
[[[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], [0, 0, 0], [0, 0, 0]]]
In [1338]:stack[0]Out[1338]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
In [1339]:stack[0][2]=3In [1340]:stackOut[1340]: 
[[[0, 0, 0], [0, 0, 0], 3],
 [[0, 0, 0], [0, 0, 0], 3],
 [[0, 0, 0], [0, 0, 0], 3],
 [[0, 0, 0], [0, 0, 0], 3]]
In [1341]:stepOut[1341]: [[0, 0, 0], [0, 0, 0], 3]

When you use alist*n to create new list, the new list contains multiple pointers to the same underlying object. As a general rule, using *n to replicate a list is dangerous if you plan on changing values later on.

If instead I make an array of the right dimensions I don't have this problem:

In [1342]: np.zeros((4,3,3),int)
Out[1342]: 
array([[[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

         ...
        [0, 0, 0]]])

Or in list form:

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

If I assign a value in this list, I only change one item:

In [1344]: stack=np.zeros((4,3,3),int).tolist()
In [1345]: stack[0][2]=3
In [1346]: stack
Out[1346]: 
[[[0, 0, 0], [0, 0, 0], 3],
 [[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]]]

I really should have used stack[0][2][1]=3, but you get the idea. If I make the same assignment in the array form I end up changing a whole row

In [1347]: stack=np.zeros((4,3,3),int)
In [1348]: stack[0][2]=3
In [1349]: stack
Out[1349]: 
array([[[0, 0, 0],
        [0, 0, 0],
        [3, 3, 3]],

       [[0, 0, 0],
         ...
        [0, 0, 0]]])

I should have used an expression like stack[0,2,:]=4.

It's probably possible to construct a triply next list like this where all initial values are independent. But this array approach is simpler.

Post a Comment for "Creating A Nested List In Python"