-13

This code is my attempt at creating an empty 3d array.

n=3
board = [[[ 0 for _ in range(n)]
            for _ in range(n)]
            for _ in range(n)]
print(board)

So, what that creates is exactly what I'm looking for a 3d array with dimensions n by n by n, but the list is filled with 0's and if I take out the 0 an error occurs. How would I create this same list but empty?

8
  • 4
    My eyes hurt... Commented Dec 19, 2016 at 16:01
  • 1
    What exactly is the format of sample output you are are looking for? My best guess is you want [[ [] for _ in range(n)] for _ in range(n)] Commented Dec 19, 2016 at 16:02
  • You can't do that. Python doesn't work that way. Commented Dec 19, 2016 at 16:03
  • 2
    What do you think an empty list of length n looks like? Commented Dec 19, 2016 at 16:04
  • 1
    @JohnGordon: It wont't create new list, But nested lists with same references Commented Dec 19, 2016 at 16:08

1 Answer 1

3

You need to use [] instead of 0 as:

n = 5
empty_list = [[[ [] for _ in range(n)] for _ in range(n)] for _ in range(n)]

Value hold by empty_list will be:

[[[[], [], [], [], []], 
  [[], [], [], [], []], 
  [[], [], [], [], []], 
  [[], [], [], [], []], 
  [[], [], [], [], []]], 
# Repeated 4 more times 

For example:

>>> empty_list[0][0][0]  # Access element with nest level 3 in list
[]
Sign up to request clarification or add additional context in comments.

6 Comments

if i was to try and access empty_list[0][0][0] it would be out of range right. I am looking for something exactly as you have done above but where that index to the third degree is accessible
I think in the above post you have created a 2d list with just extra brackets inside of it as oppose to a 3d list
Is this not a 3d list with brackets inside of it?
As per my definition of 3D; the solution I mentioned earlier was a 3D list. It is a 4D list. OR, in other words you may say 3D list with value as empty lists
If i wanted to print this in the format shown above, where every 2d list has its own line, how would i do it?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.