'pygame game of life index out of range drawing rect

I am trying to recreate Conways game of life and I have been following and trying to recreate it in pygame "tutorial" from The Coding Train challenge #85. But I have stumbled when trying to actually draw a rectangle if in my array on [i][j] == 1: when I run the file it tells me IndexError list index out of range.

import pygame
import random
 
WIDTH = 400
HEIGHT = 400
 
pygame.init()
window = pygame.display.set_mode((WIDTH,HEIGHT))
 
# create 2d array
def create_2d_list(cols, rows):
    arr = []
    for i in range(cols):
        arr.append([0] * rows)
 
    return arr
        
 
resolution = 40
 
cols = WIDTH // resolution
rows = HEIGHT // resolution
 
def main():
    global grid
    grid = create_2d_list(cols, rows)
    for i in range(cols):
        for j in range(rows):
            grid[i][j] = random.randint(0,1)
 
    draw()
    
    pygame.display.flip()
 
 
def draw():
    background = window.fill((255,255,255))
    cols = 10 * resolution
    rows = 10 * resolution
    for i in range(cols):
        for j in range(rows):
            x = i * resolution
            y = j * resolution
            if grid[i][j] == 1:
                pygame.draw.rect(window,(0,0,0), pygame.Rect(x , y, resolution, resolution))
 
 
 
if __name__ == "__main__":
    main()
 

And error tells me:

line 46, in draw if grid[i][j] == 1: IndexError: list index out of range

I have tried debugging it and issue seems to happen after the first cycle of for cycle j but I can't pinpoint the issue Would be glad if anyone could help me with this.



Solution 1:[1]

You've recreated the cols and rows variables:

cols = 10 * resolution

Just delete those lines.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 quamrana