Python 2.7 creating a multidimensional list

Posted by poop on Stack Overflow See other posts from Stack Overflow or by poop
Published on 2012-11-19T04:56:18Z Indexed on 2012/11/19 5:00 UTC
Read the original article Hit count: 123

Filed under:
|

I don't know why I am having so much trouble creating a 3 dimensional list.

I need the program to create an empty n by n list. So for n = 4:

x = [[[],[],[],[]],[[],[],[],[]],[[],[],[],[]],[[],[],[],[]]]

I've tried using:

y = [n*[n*[]]]    
y = [[[]]* n for i in range(n)]

Which both appear to be creating copies of a reference. I've also tried naieve application of the list builder with little success:

y = [[[]* n for i in range(n)]* n for i in range(n)]
y = [[[]* n for i in range(1)]* n for i in range(n)]

I've also tried building up the array iteratively using loops, with no success. In my rapid flurry of attempts to not post something stupidly easy to SO, I came upon a solution:

y = []
for i in range(0,n):
    y.append([[]*n for i in range(n)])

Is there an easier/ more intuitive way of doing this?

© Stack Overflow or respective owner

Related posts about list

Related posts about python-2.7