0

I am trying to create a 4x4 array looking something like this:This is a javascript code that I'm trying to create into python

[0, 1, 2, 3]

[4, 5, 6, 7]

[8, 9, 10, 11]

[12, 13, 14, 15]

    height = 4
    width = 4

    num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

    for i in range(0, height * width, 4):
        row = []
        for j in range(i, i + width, 1):
            row.append(num[j])
            print(row)
  • 2
    what is your question? – Dave Costa Aug 09 '21 at 17:34
  • Basically I am trying to get the array to print out in the console reading [0, 1, 2, 3] [4, 5, 6, 7] [8, 9, 10, 11] [12, 13, 14, 15] however my console is printing out as: [0] [0, 1] [0, 1, 2] [0, 1, 2, 3] [4] [4, 5] [4, 5, 6] [4, 5, 6, 7] [8] [8, 9] [8, 9, 10] [8, 9, 10, 11] [12] [12, 13] [12, 13, 14] [12, 13, 14, 15] I am not to familiar with python for loops so I am trying to figure out what I am doing wrong – cyber_cloud Aug 09 '21 at 17:36
  • Okay, and what is your *question*? What happened when you tried to run the code, and how is that different from what you wanted? And why does this result confuse you - why do you need help? What happened when you tried to trace through the logic of the code and look for logical errors? What happened when you tried checking the values of variables at various points during the execution? Do they match what you expected? – Karl Knechtel Aug 09 '21 at 17:38
  • Does https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks answer your question? – Karl Knechtel Aug 09 '21 at 17:39
  • @cyber_cloud Your immediate problem then appears to be simply that you have the `print()` call inside the inner loop. You should unindent it so that it is called after the inner loop completes. – Dave Costa Aug 09 '21 at 17:56
  • @DaveCosta Thank you that small fix helped me get what I was looking for. I'll have to remember that from now on – cyber_cloud Aug 09 '21 at 18:02

3 Answers3

0

If you are looking for alternative suggestions, I would recommend using numpy:

import numpy as np

height, width = 4, 4
num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

array = np.array(num).reshape((height, width))
print(array)

Output:

array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
aminrd
  • 4,300
  • 4
  • 23
  • 45
0

Check this out:

num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
def check(num,each=4):
    for i in range(0,num,each):
        print(num[i:i+4])
check(16,4)
0

There is a little mistake...!

height = 4
width = 4
num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for i in range(0, height*width, 4):
    row = []
    for j in range(i, i+width):
        row.append(num[j])
    print(row) # this statement should be outside the second for loop
Thushan D.
  • 16
  • 3