Neo
Neo

Reputation: 31

python: make 3 dimensional list element values all to zero

I want to make all elements of a 3 dimensional array to zero without calling three for loops.

list= [[[1,2],[3,4,11]],[[5,6,12,13],[7,8,14]]]

into

list= [[[0,0],[0,0,0]],[[0,0,0,0],[0,0,0]]]

I don't want to call 3 for loops to do individual assignment. Is there a single function to do this operation.

Upvotes: 0

Views: 281

Answers (2)

Kasravnd
Kasravnd

Reputation: 107347

In pure python you have to loop. But if you can use another numerical libraries you can use numpy:

In [13]: arr = np.array([[[1,2],[3,4]],[[5,6],[7,8]]])

In [15]: arr = np.zeros(arr.shape)

In [16]: arr
Out[16]: 
array([[[ 0.,  0.],
        [ 0.,  0.]],

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

As @ Blckknght mentioned in comment, if you want to change the items in-place you better to use a simple slice assignment, instead of creating new array using np.zeros():

In [4]: arr[:] = 0

In [5]: arr
Out[5]: 
array([[[0, 0],
        [0, 0]],

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

Upvotes: 1

J. P. Petersen
J. P. Petersen

Reputation: 5031

You can use list comprehensions:

[[[0 for k in m] for m in l] for l in lst]

Upvotes: 1

Related Questions