btror
btror

Reputation: 125

How to print all the elements of a 2d array in python with a different number of rows than columns?

I have a 2d array in python. I initialized it like this:

rows = 5
cols = 5
array = [[None for _ in range(rows)] for _ in range(cols)]

I want to add elements to each spot in the array. I did it like this:

for i in range(rows):
    for j in range(cols):
        array[i][j] = " 0 "

I also have a function that prints the array. It looks like this:

def printGrid():
    for i in range(rows):
        for j in range(cols):
            print(array[i][j], end='')
        print("")

When the number of columns matches the number of rows it works and the output looks something like this:

enter image description here

The problem is when the number of cols is different than the number of rows I get this error (for example, if rows=5 and cols=4):

enter image description here

What am I doing wrong?

Upvotes: 1

Views: 2335

Answers (2)

kawwasaki
kawwasaki

Reputation: 91

When initializing an array, the inner array specifies the columns and the outer specifies the rows, like so: array = [[None for x in range(cols)] for y in range(rows)]

Complete Code:

rows = 7
cols = 6
array = [[None for x in range(cols)] for y in range(rows)]

for i in range(rows):
    for j in range(cols):
        array[i][j] = " 0 "

for k in range(rows):
    for l in range(cols):
        print(array[k][l], end='')
    print("")


Upvotes: 2

Krishna Chaurasia
Krishna Chaurasia

Reputation: 9590

Your list is initialized incorrectly.

It should be like:

array = [[None for _ in range(cols)] for _ in range(rows)]

which means create rows number of list where each row list has cols elements.

Upvotes: 2

Related Questions