简体   繁体   中英

List assignment index out of range Python

When i try to run this code,I am getting list assignment index out of range error in the line 7.

import random
    Matrix = [[0 for x in range(37)] for x in range(37)] 
    for i in range(0,37):
        for k in range(3,16):
            for j in range(0,k):
                y=random.randint(0,37)
                Matrix[i][y]=1
    for row in Matrix:
        print (row)

What am i doing wrong? Any help would be appreciated.Thanks.

0 <= random.randint(0,37) <= 37 is always True.

I mean y will be 37!

but Matrix are list of list which has indexes 0 from 36 not 37

if you get the Matrix[i][37] , then you will see index out of range error !!

FIX

         y=random.randint(0,37)

to

         y=random.randint(0,36)

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