Mehdi Rezzag Hebla
Mehdi Rezzag Hebla

Reputation: 334

Python how do I print 2D grid elements without nested loops?

new python learner here. I tried to print each element in my 2D grid by using 2 variables in my loop instead of nested loop, here is the code:

number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]

for r, c in number_grid:
print(r, c)

and I get this error :

 for r, c in number_grid:
ValueError: too many values to unpack (expected 2)

I am also interested in understanding the meaning and the reason as to why I get this error message. Thank you.

Upvotes: 0

Views: 441

Answers (2)

Kadir Şahbaz
Kadir Şahbaz

Reputation: 503

There is a nice explanation here on why you get that error and how to solve this.

To print numbers without nested loops, you can use the following ways:

number_grid = [[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9],
               [0]]

for grid in number_grid:
    print(*grid)

# 1 2 3
# 4 5 6
# 7 8 9
# 0

Or:

number_grid = [[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9],
               [0]]

print(' '.join(map(str, list(itertools.chain(*number_grid)))))

# 1 2 3 4 5 6 7 8 9 0

Upvotes: 1

Eric Truett
Eric Truett

Reputation: 3010

By calling for r,c in number_grid, you are unpacking the inner list as you iterate over the outer list. The problem is that the first inner list [1, 2, 3] has 3 elements, and you are trying to unpack it into only two variables, r and c. You will also get an error in the final inner_list [0], which only has 1 element, thus leaving nothing to unpack into c.

You might have more success by iterating over the outer list. A starting point would be something like the code below, where each row is a list that you can print or modify appropriately.

for row in number_grid: 
    print(' '.join([str(item) for item in row]))

Upvotes: 2

Related Questions