3

I am trying to populate a 3D list in the following fashion:

l1 = []
for _ in range(5):
    l2 = []
    for _ in range(10):
        l2.append([0] * 20)
    l1.append(l2)

It looks really disgusting and I feel like there should be some way to use higher order function or anon functions or list comprehension to achieve this. Can any python ninjas show me how to achieve this?

Thanks!

3 Answers 3

3

You can consider using numpy if you plan on "vectorized" calculations:

l1 = np.zeros((5, 10, 20))

The docs.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer & help! straight list comprehension is enough for my case, but will def keep that in mind for future reference.
2

Try this:

[[[0]*20 for _ in xrange(10)] for _ in xrange(5)]

The answer initially given by @zch has a very serious problem: it copies the same list over and over in the resulting matrix, so changes in one position will be reflected simultaneously in other unrelated positions!

My solution is indeed equivalent to your definition of l1, but written a bit more concisely thanks to the use of list comprehensions. Notice that we're not using the iteration variables, so it's ok to use _ as placeholder. And, assuming you're using Python 2.x, it's a better idea to use xrange because we don't need the list created by range. (If using Python 3.x, it's ok to use range)

Comments

1
>>> l1 == [[[0]*20]*10]*5
True

But this way there is aliasing - for example changing a[0][1][2] would also change a[4][5][2], to avoid it, copies are necessary:

[[[0]*20 for i in range(10)] for j in range(5)]

3 Comments

NO. This is is a list of 5 references to a list of 10 references to a third list of 20 zeros. A total of three lists is created. l1[0] is l1[1], l1[0][0] is l1[1][2], etc. Demonstration: gist.github.com/anossov/5000464
@Jin, Do consider looking into numpy like Lev suggested. The learning curve is steeper than Python, but I bet now that you have your 3D list, your next question is going to be "Okay now how do I..." and the answer is going to be "use numpy".
@Jon-Eric I will def look into numpy next after I figure out where I'm going with this :]

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.