简体   繁体   中英

IndexError: list index out of range in matrix printing

in_num=int(input())
n_list=[[0 for x in range(in_num) for y in range(in_num)]]

print(n_list)
for row in range(in_num):
    for col in range(in_num):
        print(n_list[row][col],end='\t')
    print()  

When I run this code I get:

5
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
0   0   0   0   0   
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-10-ef7ccb495ef4> in <module>
      4 for row in range(in_num):
      5     for col in range(in_num):
----> 6         print(n_list[row][col],end='\t')
      7     print()

IndexError: list index out of range

Why I am getting this error and how can I recover this error?

Hope this helps!

can you update the following?

n_list = [[0 for x in range(in_num) for y in range(in_num)]]

To below

n_list = [[0 for x in range(in_num)] for y in range(in_num)]

Explanation: IMO, you are trying to create a 2D Matrix of zero's but you ended up creating a simple nested list of 1 element.

Instead of [[0, 0], [0, 0]] you are creating [[0, 0, 0, 0]]. In this second output, the shape is this is 1 X 4 where as the first has 2 X 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM