0

I am new to Python and I am trying to add elements to a 3D list.

def getHoughSpace(self):
        space = [[[]]]
        for i in range(0, len(self.xs)):
            rho = self.getRho(self.xs[i], self.ys[i], self.zs[i])
            space.append([Cell(rho, 0)])
            for j in range(0, len(self.ys)):
                theta = self.getTheta(self.xs[j], self.ys[j], self.zs[j])
                space[i].append([Cell(theta, 0)])
                for k in range(0, len(self.zs)):
                    phi = self.getPhi(self.xs[k], self.ys[k])
                    space[i][j].append([Cell(phi, 0)]) # error happens here

However, when i=1, j=0, and k=0, my program crashes with the error:

AttributeError: Cell instance has no attribute 'append'

Why is this happening? How can I get passed i=0, j=0, and k=0 but not when i=1? Obviously, I am accessing a Cell at space[i][j], but I want to access the list of Cells.

  • An interesting note is that if I comment out the error line, it runs. So why does the problem occur only in the 3rd dimension?

1 Answer 1

1

You might want to append elements at the end, for the three dimensional list:

space = []
space.append([])
space[i].append([])
space[i][j].append(<element>)

Or you can use numpy:

import numpy as np
space = np.empty((len(self.xs), len(self.ys), len(self.zs)), dtype=object)
Sign up to request clarification or add additional context in comments.

2 Comments

I used numpy to get it working. I would note that you cannot use append anymore sense you have allocated an array. You must use space[i][j][k] = Cell(phi, 0).
@TrevorHutto The problem, with original program is: space.append([Cell(rho, 0)]) which disturbs the dimensionality of list, if you print it you can see another list being added as element instead of list of list.

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.