Quiz nested3d, I don't get it

Hi Folks,

Again beginner question. I am having a hard time understanding this question in the quizes. I ran it through visual code editor with python extension and debugger but am still at a loss. Probably something very simple that I am missing:

type ormatrix = [[[k for k in range(3)] for j in range(3)] for i in range(3)]
print(matrix[1][2]) paste code here

Let’s spread it out to make more sense of it

ormatrix = [
    [
        [k for k in range(3) ]
        for j in range(3)
    ]
    for i in range(3)
]

What we have is a triple-nested list comprehension.
Python will work from the inside out.

  • [k for k in range(3) ] - yields [0, 1, 2]
  • then
    for j in range(3) - will execute the above 3 times putting the inner result into a new list, so that will be [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
  • finally
    for i in range(3) - will execute all the above 3 times putting the inner result into a new list, so that will be
    [
      [[0, 1, 2], [0, 1, 2], [0, 1, 2]],
      [[0, 1, 2], [0, 1, 2], [0, 1, 2]],
      [[0, 1, 2], [0, 1, 2], [0, 1, 2]],
    ]
    

So ormatrix[1][2] will be the second row, third item, which is [0, 1, 2]

1 Like

Thank you I see what it is doing now.

cheers

but you mean 0 1 2? right?

Yes, I do. Slip of the hand - edited it now

1 Like