manipulating 3D array in python

Question:

I’m getting the following error when I run the code given below. Still learning Python, so where am I going wrong in my understanding ? What is the fix?

Traceback (most recent call last):
File "main.py", line 26, in
cube[1:3, 1:3]= [‘‘, ‘‘, ‘*’]
TypeError: list indices must be integers or slices, not tuple

cube = [[[':(', 'x', 'x'],
         [':)', 'x', 'x'],
         [':(', 'x', 'x'],
         [':(', 'x', 'x']],

        [[':)', 'x', 'x'],  
         [':(', 'x', 'x'], # --> want this element to be ['*', '*', '*']
         [':)', 'x', 'x'], # --> want this element to be ['*', '*', '*']
         [':(', 'x', 'x']],

        [[':(', 'x', 'x'],
         [':)', 'x', 'x'], # --> want this element to be ['*', '*', '*']
         [':)', 'x', 'x'], # --> want this element to be ['*', '*', '*']
         [':(', 'x', 'x']],
         
        [[':(', 'x', 'x'],
         [':)', 'x', 'x'],
         [':)', 'x', 'x'],
         [':(', 'x', 'x']],
         
        [[':(', 'x', 'x'],
         [':)', 'x', 'x'],
         [':)', 'x', 'x'],
         [':(', 'x', 'x']]]
         
cube[1:3, 1:3] = ['*', '*', '*']

print(cube)
Asked By: Sohini De

||

Answers:

You are using nested lists, which are not truly 3D arrays. I would suggest you use numpy to get arrays that actually support that kind of slice based access:

import numpy as np
cube = np.array([[[':(', 'x', 'x'],
         [':)', 'x', 'x'],
         [':(', 'x', 'x'],
         [':(', 'x', 'x']],

        [[':)', 'x', 'x'],  
         [':(', 'x', 'x'], 
         [':)', 'x', 'x'], 
         [':(', 'x', 'x']],

        [[':(', 'x', 'x'],
         [':)', 'x', 'x'], 
         [':)', 'x', 'x'], 
         [':(', 'x', 'x']],
         
        [[':(', 'x', 'x'],
         [':)', 'x', 'x'],
         [':)', 'x', 'x'],
         [':(', 'x', 'x']],
         
        [[':(', 'x', 'x'],
         [':)', 'x', 'x'],
         [':)', 'x', 'x'],
         [':(', 'x', 'x']]])
         
cube[1:3, 1:3] = ['*', '*', '*']

print(cube)

Output:

[[[':(' 'x' 'x']
  [':)' 'x' 'x']
  [':(' 'x' 'x']
  [':(' 'x' 'x']]

 [[':)' 'x' 'x']
  ['*' '*' '*']
  ['*' '*' '*']
  [':(' 'x' 'x']]

 [[':(' 'x' 'x']
  ['*' '*' '*']
  ['*' '*' '*']
  [':(' 'x' 'x']]

 [[':(' 'x' 'x']
  [':)' 'x' 'x']
  [':)' 'x' 'x']
  [':(' 'x' 'x']]

 [[':(' 'x' 'x']
  [':)' 'x' 'x']
  [':)' 'x' 'x']
  [':(' 'x' 'x']]]
Answered By: FlyingTeller
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.