Constructing a list of list of arrays?

Viewed 145

In Python I'm trying to create a list, of lists of 1x2 arrays. How would I go about constructing the following list with for loops?

[ [ [0 0] , [0 1] , [0 2] , [0 3] ],
  [ [1 0] , [1 1] , [1 2] , [1 3] ],
  [ [2 0] , [2 1] , [2 2] , [2 3] ],
 [ [3 0] , [3 1] , [3 2] , [3 3] ] ]

It seems like a pretty trivial problem so I've tried a number of nested-loop methods to attempt to create this with no luck. Below is my closest attempt.

```
    column = []
    solarray = []
    
    for i in range(4):
        for j in range(4):
            sol = [i,j]
            
        solarray.append(sol)
        column.append(solarray)
        
           
    print('Here is the last 1x2 list')      
    print(sol)
    print('')
    print('Here is the list containing all of the 1x2 lists')
    print(solarray)
    print('')
    print('Here is the list containing the 4 lists of 1x2 lists')
    print(column)
```

With an output:

```
'Here is the last 1x2 list'
[3, 3]

'Here is the list containing all of the 1x2 lists'
[[0, 3], [1, 3], [2, 3], [3, 3]]

'Here is the list containing the 4 lists of all 1x2 lists'
[[[0, 3], [1, 3], [2, 3], [3, 3]], [[0, 3], [1, 3], [2, 3], [3, 3]], [[0, 3], [1, 3], [2, 3], [3, 3]], [[0, 3], [1, 3], [2, 3], [3, 3]]]
```

Also note that I did not specify a 1x2 array in the code, but a list because that was the only way to get this close answer. Furthermore, my version gives the final j index instead of iterating through the j's as the loop goes through the specified range.

What am I doing wrong?

3 Answers
column = []
solarray = []

for i in range(4):
    solarray = []
    for j in range(4):
        solarray.append([i,j])
    column.append(solarray)

print('Here is the list containing the 4 lists of 1x2 lists')
print(column)

Use list comprehension.

solarray = [ [ [a,b] for b in range(4) ] for a in range(4) ]

You need to initialise the solarray inside the outer loop and indent it as suggested.

column = []
for i in range(4):
    solarray = []
    for j in range(4):
        sol = [i,j]
        solarray.append(sol)
    column.append(solarray)

print(column)

This will yield what you want:

In [5]: print(column)
[[[0, 0], [0, 1], [0, 2], [0, 3]], 
 [[1, 0], [1, 1], [1, 2], [1, 3]], 
 [[2, 0], [2, 1], [2, 2], [2, 3]], 
 [[3, 0], [3, 1], [3, 2], [3, 3]]]

Cheers!

ps. I manually addded some to the output for readability

Related